Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a rails resource with a parameter for new action?

I have a model named Entree for which the new action needs a parameter, the id of another model named Cave. I don't want to nest Entree in Cave since Cave is already nested.
What I did was declaring the resource Entree as follow in routes.rb:

resources :entrees, :except => [:new]
match "/entrees/new/:id", :to => "Entrees#new", :as => 'new_entree'

That works, but the problem is when there's an error in the create action, I want to display the page again with the invalid input. But since there's no new action, I must do a redirect_to new_entree_path, which does not keep the user input.

I have tried the following (simplest) route:

resources :entrees

But then the path http://localhost:3000/entrees/new/32 returns an error:

No route matches [GET] "/entrees/new/32"

The question is, how can I declare the Entree resource in the routes file with a parameter for the new action ?

like image 408
Antoine Avatar asked Mar 20 '12 20:03

Antoine


Video Answer


2 Answers

Rails has a route helper called path_names that does this:

resources :entrees, path_names: { new: 'new/:id' }
like image 58
sbonami Avatar answered Nov 03 '22 23:11

sbonami


To improve gwik 's solution (which in fact didn't work for me):

resources :things, except: [:new] do
  new do
    get ':param', to: 'things#new', as: ''
  end
end

It gets you new_thing_* helpers (instead of new_things_*) for free.

like image 35
Vittorius Avatar answered Nov 03 '22 23:11

Vittorius