2011-10-04 40 views
1

我有用戶模型,事件模型,事件優先級模型和事件類型模型。型號代碼如下:在Rails控制檯中測試模型關聯時出現奇怪的結果

class Event < ActiveRecord::Base 

    belongs_to :user 
    belongs_to :event_priority 
    belongs_to :event_type 

    attr_accessible :name, :raised_date, :location, :description, :longtitude, :latitude 
    attr_protected :raised_user_id, :event_priority_id, :event_type_id 
end 

class EventPriority < ActiveRecord::Base 

    has_many :events 
    has_many :users, :through => :events 
    has_many :event_types, :through => :events 

end 

class EventType < ActiveRecord::Base 

    has_many :events 
    has_many :users, :through => :events 
    has_many :event_priorities, :through => :events 

end 

class User < ActiveRecord::Base 

    attr_accessor :password 
    attr_accessible :first_name, :last_name, :full_name, :password, password_confirmation 

    has_many :events, :foreign_key => "raised_user_id", :dependent => :destroy 
    has_many :event_priorities, :through => :events 
    has_many :event_types, :through => :events 

end 

任何人都可以解釋無法從以下軌道控制檯示例中的事件返回到用戶?

irb(main):027:0> @user = User.find(2) 
=> Returns the user with an ID of 2. 

irb(main):028:0> @user.events 
=> Returns all events for that user. 

irb(main):029:0> @user.events.first.user 
=> nil --HUH???? 

irb(main):031:0> @event = @user.events.first 
=> Saves and returns the first event created by the user. 

irb(main):032:0> @event.user 
=> nil --Again, WHY?? 

irb(main):033:0> @events = Event.all 
=> Saves and returns all events. 

irb(main):035:0> @events.first.user 
NoMethodError: You have a nil object when you didn't expect it! 
You might have expected an instance of Array. 
The error occurred while evaluating nil.first 
     from (irb):35 
     from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activemodel-3.0. 
6/lib/active_model/attribute_methods.rb:279 -- AGAIN, WHY? 
+1

你可以發佈':user'和':event'的模型關聯嗎? –

+0

好吧,我明白了!所以a:custom_key必須在Rails模型關聯的兩邊指定,在我的例子中是has_many和belongs_to。 –

回答

1

你有一個很好的理由不只是使用user_id作爲events表的外鍵? (這是什麼原因造成您的問題)

嘗試添加foreign_key選項在事件類以及

+0

真棒傢伙,感謝您的幫助,現在全部排序。 –

0

您可以從用戶獲取事件,因爲你已經告訴「用戶的has_many事件」關聯使用您的自定義外鍵。你不能回頭,因爲你沒有告訴「Event belongs_to User」關聯使用該自定義密鑰。因此,它期望它找不到默認的「user_id」鍵,所以它無法恢復。

我很驚訝它優雅地處理它(通過返回零),實際上 - 我會期望它在這一點上拋出異常。

我恐怕不知道你的第二個問題。我只能猜測,你以某種方式設置@eventsnil缺失IRB線#34 ...

希望有所幫助!

+0

所以我應該將:foreign_key =>「raised_user_id」移動到Events模型中,還是應該在User和Events模型中使用? –

+0

@raouldeveloper - 它需要在兩個地方。但是,如果你只是使用屬性'user_id',你就不需要它在任何地方(見klochner的答案)。任何你不能這樣做的理由? –

+0

行了!關於關聯的官方Rails指南並不清楚這兩種模式中的外鍵都必須在代碼中。我想在將來使用預期的user_id會更好......感謝一百萬! –

相關問題