我认为这可能是一个简单的修复,我只是不知道该怎么做。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