Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How to get a custom restful member route without ID

I'm working on a project where users can upload videos through a simple form and additionally by FTP to a certain directory and then simply choose the file from the FTP directory instead of uploading it through the form.

I got the following, pretty standard setup for a videos_controller:

# routes.rb
resources :videos

# new.html.rb
form_for(@video) do |f|
  ...
end

The restful actions in the controller are all working and just standard behaviour. The upload works, that's not the problem. The problem is if I do the following:

# routes.rb
resources :videos do
  member do
    post :from_ftp
  end
end

# new.html.rb
form_for(@video, :url => from_ftp_video_url) do |f|
  ...
end

I get the error: No route matches {:action=>"from_ftp", :controller=>"videos"}, because the generated route looks like this:

from_ftp_video POST   /videos/:id/from_ftp(.:format)        videos#from_ftp

which seems right, since it's a member route. But I don't need the :id part of the URL, since I'm creating a new Video object, not through a form but simply by using the file from the FTP directory... So it basically is another create action, that's why I would like to do it as a POST request...

So how do I tackle this the best way?

like image 399
Vapire Avatar asked Mar 15 '13 13:03

Vapire


2 Answers

Although the selected answer is correct for Vapire's situation, it doesn't necessarily answer the title question. If you came here looking for how to get member actions without an ID because you don't need an ID, the answer is a little different.

Say you implemented authentication that sets current_user. You let users edit their own profile only. In that case users/:id/edit doesn't make sense because :id is dictated by the current_user method. In this case /users/edit makes more sense.

You can change your routes.rb file to create member actions without an id in the path.

...instead of this...

resources :user

...use this (note the plurality of resource)...

resource :user
like image 66
IAmNaN Avatar answered Nov 23 '22 22:11

IAmNaN


The way to understand member and collection routes is this:

  • Member routes do something to an object that you have.
  • Collection routes do something to the set of all objects.

So when we consider what the create route would be, it's a collection route, because it's adding a new object to the collection!

So your from_ftp method should also be a collection route, because it's adding to the collection.

Also, you might want to consider if you can accommodate the FTP functionality within your existing create method - it might be neater.

like image 39
thomasfedb Avatar answered Nov 24 '22 00:11

thomasfedb