20

我對Rails開發比較新,而且我有一個小的關聯問題。我想指出一個與它所鏈接的模型不同的協會。Rails belongs_to協會(with:class_name)返回無

我有以下2種型號:

class User < ActiveRecord::Base 
    has_many :events 
end 

class Event < ActiveRecord::Base 
    belongs_to :admin, :class_name => "User" # So we can call event.admin to retrieve the User who owns this Event 
end 

我建立一個用戶,如下所示:

event = event.create! :title => "New Event" 

user = User.create! :username => "thinkswan" 
user.events << event 
user.save 

當我跳進控制檯收到以下:

irb> user = User.find(1) 
irb> user.events 
=> [#<Event id: 1, title: "New Event", user_id: 1, created_at: "2011-06-09 06:41:09", updated_at: "2011-06-09 06:41:10">] 

irb> event = Event.find(1) 
irb> event.user_id 
=> 1 
irb> event.admin 
=> nil 

任何人都可以解釋爲什麼admin協會沒有返回它指向的用戶?謝謝!

+5

+1,包括在你的問題大個子一個很好的例子。我終於明白什麼':'belongs_to'的class_name'選項意思是.. [docs](http://guides.rubyonrails.org/v2.3.11/association_basics.html)中的例子不太清楚 – abbood 2013-04-21 14:43:33

回答

46

您需要同時指定:class_name:foreign_key,例如:

belongs_to :admin, :class_name => "User", :foreign_key => "user_id" 
+0

我知道這將是一件簡單的事情。非常感謝,Jits!我很感激! – 2011-06-09 15:44:12

+0

沒問題。一個要注意的未來:) – Jits 2011-06-09 15:45:33

+0

爲你們歡呼,我終於明白了:admin是變量名,而不是class_name! – njzk2 2013-08-13 13:19:35