Rails 4 new form defaults from params -
i using form_for
in _form.html.erb
view in order create form both edit , new actions, per standard scaffold.
i have model owner has_many pets.
i put html link on views/owners/show.html.erb
create new pet said owner. link point new action of pets_controller.rb
when accessed render view in pets/new.html.erb
what want happen the owner_id
passed link in url new action of pets_controller.rb
, used default collection_select in pets/new.html.erb
so have link create new pet because link on specific owner page, want form create new pet have owner set, user not have select list.
this has done without changing behaviour of edit action/view in pets.
i know can pass arguments access them in controller via params, create variables in action passed view. can manually check default , set in view. not need assistance in coding if solution.
is there better way this? format can pass params such view pick them up? without manually editing controllers , views?
while personal inclination said , pass parameter in link helper , access params array in pets view, may find perfect opportunity explore nested resources. essentially, declare owners/:owner_id/pets/:pet_id route with:
resources :owners resources :pets end
you link route, , reference :owner_id without having append query string uri (making cleaner reuse).
this more work you, potentially more extensible (and more inline rails way of doing things).
revision
added following regarding link helpers comments, wanted reflect in answer well.
to show pet should be:
<%= link_to owner_pet_path( owner_variable, pet_variable) %>
to view pets' index index should be:
<%= link_to owner_pet_path( owner_variable ) %>
the answer given to question fantastic.
Comments
Post a Comment