我一直收到此错误
ActiveRecord::RecordNotFound in LocationsController#index
Couldn't find Location without an ID
@location= Location.find(params[:id])
我正在使用gmaps4rails并在infowindow partial中显示信息。我可以很好地显示位置地址,但是当我开始尝试显示厨师信息时,我得到了上述错误。
位置模型:
class Location < ActiveRecord::Base
acts_as_gmappable
belongs_to :chef
validates :chef_id, :zipcode, :address, presence: true
def gmaps4rails_address
"#{address}, #{zipcode}"
end
end
Chef Model:
class Chef < ActiveRecord::Base
has_many :meals, dependent: :destroy
has_one :location
end
地点控制器:
class LocationsController < ApplicationController
def index
@location= Location.find(params[:id])
@chef = Chef.find(@location.chef_id)
@locations = Location.all
@json = @locations.to_gmaps4rails do |location, marker|
marker.infowindow render_to_string(:partial => "/locations/infowindow", :locals => { :location => location})
marker.title "#{location.address}"
marker.json({ :zipcode => location.zipcode})
end
end
def self.save_all
Location.all.each { |location| location.save! }
end
end
infowindow partial
<%= location.address %>
<% @chef.each do |chef| %>
<%= chef.name %>
<% end %>
任何人都有帮助......请在我吹电脑之前......
答案 0 :(得分:1)
您收到错误
Couldn't find Location without an ID
on
@location= Location.find(params[:id])
在您的index
行动中排成一行,因为您未:id
传递任何params
所以params[:id] is nil
<强>更新强>
假设您在routes.rb
中定义了嵌套路由,即locations
嵌套在chefs
路由中,那么您应该直接在params中接收chef_id
。
然后,您的index
操作应该是
def index
@chef = Chef.find(params[:chef_id])
@locations = Location.all
@json = @locations.to_gmaps4rails do |location, marker|
marker.infowindow render_to_string(:partial => "/locations/infowindow", :locals => { :location => location})
marker.title "#{location.address}"
marker.json({ :zipcode => location.zipcode})
end
更新2
根据与OP的聊天会话,OP没有任何嵌套路由。所有想要的OP都是为特定位置显示chef.name
。
在index
视图中,
<%= @locations.each do |location| %>
<%= location.chef.try(:name) %>
<% end %>