I think this is probably an easy fix, I'm just not sure what to do.
I have the following:
User model
class User < ActiveRecord::Base
has_many :events
def full_name
[first_name, last_name].join(" ")
end
end
Event model
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
I get the following error when I run the query:
NoMethodError in CalendarController#index
undefined method `full_name' for nil:NilClass
But, when I am in Rails Console, if I run the method:
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"}
As you can see, the "event_creator" works with no problem in the Rails console.
Any ideas on what is going on here and what I need to change?
Thanks very much!
You would get this error if Event.user_id
is nil, meaning there is no user assigned to the Event.