Ruby on Rails: link_to not having appropriate ID
So, I got this error
Couldn't find MenuBar开发者_StackOverflow社区 with ID=add_page_to_menu
But my code for the link that creates that error is as follows:
<%= link_to "add",
:controller => "admin/menu_bars",
:action => "add_page_to_menu",
:page => page.id,
:menu => @menu_bar.id %>
The URL that I get the error on is
http://example.com/admin/menu_bars/add_page_to_menu?menu=1&page=1
it should look something like example.com/admin/menu_bars/add_page_to_menu/1?menu=1&page=1
(I think, I could be wrong, seeing as how its not working =(
the corresponding action in the controller:
def add_page_to_menu
@menu_bar = MenuBar.find(params[:menu])
@page = LinkPage.find(params[:page])
@menu_bar.link_pages << @page
if @menu_bar.save
format.html { render :action => "edit" }
else
format.html { render :action => "edit" }
format.xml { render :xml => @menu_bar.errors, :status => :unprocessable_entity }
end
end
Routes:
map.namespace "admin" do |admin|
admin.root :controller => :site_prefs, :action => :index
admin.resources :site_prefs
admin.resources :link_pages
admin.resources :menu_bars
end
Your route is going to eval to
http://example.com/admin/menu_bars/:id?menu=1&page=1
so Rails is looking for a MenuBar
with an ID of add_page_to_menu
. You need to add a member method to the routes for your custom action. The routes should look like this:
map.namespace "admin" do |admin| admin.root :controller => :site_prefs, :action => :index admin.resources :site_prefs admin.resources :link_pages admin.resources :menu_bars, :member => { :add_page_to_menu => :get } end
and the link_to
should look something like this:
link_to("add", menu_bar_add_page_to_menu_path(@menu_bar, :page => @page.id)
and the url produced should look something like this:
http://example.com/admin/menu_bars/1/add_page_to_menu?page=1
There's still some optimization to be done in that, but I think it will get you beyond this issue at least.
精彩评论