Pass additional parameters to a controller
I have this link to create a new page:
<p><%= link_to "Add a page"开发者_开发技巧, :action => "new" %></p>
The code called in the controller is this:
def new
@page = Page.new
@visuals = Visual.find(:all)
end
I would like to pass an additional parameter to pre-set a field in the form, something like this:
<p><%= link_to "Add a page", :action => "new/parent_id/2" %></p>
and in the controller
def new
@page = Page.new
@page.parent_id = params[:parent_id]
@visuals = Visual.find(:all)
end
link_to "new", :action => 'new', :parent_id => 1
... will give you:
/controller/new?parent_id=1
If you mess with the routes, you could do:
map.new_page_from_parent "/new_from_parent/:parent_id"
... and use like so:
link_to "new", new_page_from_parent_path(:parent_id => 1)
# gives
/new_from_parent/1
# accessed via
params[:parent_id] => 1
To get a new parameter without changing routes, just pass it in as a query string:
new?parent_id=2
then it will be available to you as params[:parent_id]
精彩评论