2014-01-31 18 views
0

我認爲這可能是一個簡單的修復,我只是不知道該怎麼做。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的控制檯沒有問題。

關於這裏發生了什麼以及我需要更改的任何想法?

非常感謝!

回答

1

如果Event.user_id爲零,表示沒有用戶分配給該事件,則會出現此錯誤。

+0

良好的通話!這就是它,謝謝! – Dodinas

0
:event_creator => self.user.full_name 
相關問題