在使用 Rails 3.1 和 Mongoid 处理一对多关系时,我一直在为 nil:NilClass 定义未定义的方法“名称”,即使我肯定它存在。要么这是一个愚蠢的错误,要么是 Mongoid 出了点问题。让我们详细说明:
我不断收到此错误:
NoMethodError in Leads#index
Showing /app/views/leads/index.html.haml where line #19 raised:
undefined method `heat' for nil:NilClass
Extracted source (around line #19):
16: - @leads.each do |lead|
17:
18: %tr
19: %td #{lead.visit.heat}°
20: %td
21: = link_to lead.name, :controller => "leads", :action => "show", :id => lead.id
当我尝试在控制台中重现它时,它似乎工作得很好。真是让人摸不着头脑。。
以下是相关地方的代码:
-------------------------*SCHNIP*------------------------------------
class Company
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
has_one :visit
def self.get_companies
visits = Visit.get_visits
companies = self.all
visits.each do |visit|
unless companies.name.include?(visit.name)
new_company = self.new
new_company.name = visit.name
new_company.visit = visit
new_company.save
end
end
#return companies for current instance
return Company.where(:visit.exists => true)
end
end
-------------------------*SCHNIP*------------------------------------
class Visit
include Mongoid::Document
include Mongoid::Timestamps
field :heat, type: Integer
field :name, type: String
belongs_to :company
def self.get_visits
return self.all
end
end
-------------------------*SCHNIP*------------------------------------
class LeadsController < ApplicationController
def index
@selected = 'visitors'
@leads = Company.get_companies
end
end
-------------------------*SCHNIP*------------------------------------
app/views/leads/index.html.haml
- @leads.each do |lead|
%tr
%td #{lead.visit.heat}°
%td
= link_to lead.name, :controller => "leads", :action => "show", :id => lead.id
-------------------------*SCHNIP*------------------------------------