Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom :new routes using Rails 3 routing

In Rails 2 we can add custom new actions to resourceful routes, like:

map.resources :users, :new => {:apply => :get}

How do we achieve the same thing in Rails 3?

resources :users do

  get :apply, :on => :new    # does not work

  new do
    get :apply               # also does not work
  end

end

Any ideas?

like image 908
aaronrussell Avatar asked Jun 15 '10 11:06

aaronrussell


People also ask

What are nested routes in Rails?

In a nested route, the belongs_to (child) association is always nested under the has_many (parent) association. The first step is to add the nested routes like so: In the above Rails router example, the 'index' and 'show' routes are the only nested routes listed (additional or other resources can be added).

Which file can you set up your routes?

For most applications, you will begin by defining routes in your routes/web.php file. The routes defined in routes/web.php may be accessed by entering the defined route's URL in your browser.

What is resourceful routing?

In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to a specific CRUD operation in a database.


1 Answers

You can use :path_names as explained in the edge routing guide:

resources :users, :path_names => { :new => "apply" }

That will only change the path to apply, it will still be routed to the new action. I don't think changing that is explicitly supported anymore (which is probably a good thing).

If you want to keep your apply action, you should probably do:

resources :users, :except => :new do
  collection do
    get :apply
  end
end

But it leaves you wondering whether it isn't better to just rename the apply action to new.

like image 172
molf Avatar answered Nov 01 '22 15:11

molf