No route matches {:action=>“show”, :controller=>“restaurants”}

随声附和 提交于 2019-12-13 08:36:10

问题


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

resources :restaurants
resources :maps

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

views/maps/_maps_link.html.erb

<div class="map-link">
<h2><%= link_to map.restaurant.title, map.restaurant %></h2>
</div>

回答1:


You referred to restaurant_path within info_for_restaurant, which is part of MapsController. Rails met error here.

You need to either define the restaurant_path in restaurant controller, or comment out this function in maps controller at this moment.




回答2:


Your approach is wrong in several levels. Let's work on them, one at a time:

1) Your call to the route helper is wrong:

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) Calling view helpers from your controller

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.

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) } %>


来源:https://stackoverflow.com/questions/15715599/no-route-matches-action-show-controller-restaurants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!