问题描述
如果我要转到主页,请单击地图localhost:3000 / maps退出此错误没有路由匹配{:action => show,:controller => restaurants}
controllers / maps_controller.rb
If I want to go with my home page clicking on the map localhost:3000/maps gets out this error No route matches {:action=>"show", :controller=>"restaurants"}
controllers/maps_controller.rb
def index
@maps = Map.all
@json = Map.all.to_gmaps4rails do |map, marker|
marker.infowindow info_for_restaurant(map.restaurant)
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @maps }
end
end
def show
@map = Map.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @map }
end
end
private
def info_for_restaurant(restaurant)
link_to restaurant_path do
content_tag("h2") do
restaurant.name
end
end
end
routes.rb
routes.rb
resources :restaurants
resources :maps
这是我的问题的答案:
controllers / maps_controller.rb
This is answer for my question:
controllers/maps_controller.rb
def index
@maps = Map.all
@json = Map.all.to_gmaps4rails do |map, marker|
marker.infowindow render_to_string(:partial => "/maps/maps_link",
:layout => false, :locals => { :map => map})
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @maps }
end
end
视图/地图/_maps_link.html.erb
views/maps/_maps_link.html.erb
<div class="map-link">
<h2><%= link_to map.restaurant.title, map.restaurant %></h2>
</div>
推荐答案
您的方法在多个级别上是错误的。让我们一次处理它们:
Your approach is wrong in several levels. Let's work on them, one at a time:
1)您对路由助手的呼叫是错误的:
restaurant_path
是 show
动作的路线帮助器。 show
动作需要一个 id
参数才有效。您的呼叫缺少一个参数。
restaurant_path
is the route helper for a show
action. A show
action needs an id
parameter to be valid. Your call is missing a parameter.
因此,您的代码必须是这样的:
So, your code must be something like this:
def info_for_restaurant(restaurant)
link_to restaurant_path(restaurant) do
content_tag("h2") do
restaurant.name
end
end
end
要查看每个操作所需的参数,可以运行在控制台上使用耙路
。
To see the parameters needed for each action, you can run rake routes
on the console.
但是,这并不能解决问题,因为您也是:
However, this does not solve the problem, as you're also:
2)从您的控制器调用视图助手
link_to
和 content_tag
是视图帮助器方法,您不想让控制器麻烦于视图问题。因此,解决此问题的最佳方法是将 info_for_restaurant
方法移动到帮助器,然后从视图中调用它。
link_to
and content_tag
are view helper methods, and you don't want to bother your controller with view issues. So, the best way to solve this problem is to move your info_for_restaurant
method to a helper, and call it from a view instead.
因此,现在,您的控制器将不会为<$ c $ c> @json 分配任何内容,并且视图的最后一行将如下所示:
So, now, your controller will not assign anything to @json
, and the last line of your view will look like this:
<%= gmaps4rails @maps.to_gmaps4rails {|map, marker| marker.infowindow info_for_restaurant(map.restaurant) } %>
这篇关于没有路线匹配{:action =>“ show”,:controller =>“ restaurants”}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!