我對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
協會沒有返回它指向的用戶?謝謝!
+1,包括在你的問題大個子一個很好的例子。我終於明白什麼':'belongs_to'的class_name'選項意思是.. [docs](http://guides.rubyonrails.org/v2.3.11/association_basics.html)中的例子不太清楚 – abbood 2013-04-21 14:43:33