我認爲這可能是一個簡單的修復,我只是不知道該怎麼做。Rails 4 - 未定義的方法 - 可能是一個簡單的答案
我有以下幾點:
用戶模型
class User < ActiveRecord::Base
has_many :events
def full_name
[first_name, last_name].join(" ")
end
end
事件模型
class Event < ActiveRecord::Base
belongs_to :user
def as_json(options = {})
{
:id => self.id,
:title => self.name,
:location => self.location,
:start => start_time.rfc822,
:end => end_time.rfc822,
:event_creator => user.full_name #this is what is causing the problem
}
end
end
我得到以下錯誤當我運行查詢:
NoMethodError in CalendarController#index
undefined method `full_name' for nil:NilClass
但,當我在Rails的控制檯,如果我運行的方法:
irb>> Event.find(1).as_json
irb>> => {:id=>1, :title=>"Your title", :location=>"Bermuda", :start=>"Sun, 05 Jan 2014 02:50:07 +0000", :end=>"Sun, 05 Jan 2014 02:51:46 +0000", :event_creator=>"John Smith"}
正如你所看到的,「EVENT_CREATOR」的作品,在Rails的控制檯沒有問題。
關於這裏發生了什麼以及我需要更改的任何想法?
非常感謝!
良好的通話!這就是它,謝謝! – Dodinas