Rails belongs_to association(with:class_name)返回nil

时间:2011-06-09 15:22:56

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord associations

我对Rails开发相对较新,而且我有一个小的关联问题。我想命名一个与它所链接的模型不同的关联。

我有以下两种型号:

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 个答案:

答案 0 :(得分:46)

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

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