为什么我在LocationsController #index中得到此错误ActiveRecord :: RecordNotFound

时间:2014-05-01 20:26:52

标签: ruby-on-rails ruby activerecord

我一直收到此错误

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

任何人都有帮助......请在我吹电脑之前......

1 个答案:

答案 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 %>