Ruby on Rails:如何建模用户是项目的“所有者”?

时间:2012-08-20 18:52:46

标签: ruby-on-rails

我希望能够在代码中查询 user.items item.owner

class Item < ActiveRecord::Base
  has_one :owner, :class_name => "User"
end

class User < ActiveRecord::Base
  # What goes here?
  has_many :items
end

我在Item模型中添加了一个列owner_id,如何构建User模型,以便在调用user.items时使用owner_id而不是user_id?

1 个答案:

答案 0 :(得分:2)

项表需要包含user_id列。如果您想手动设置此密钥,则应使用:

... ,:foreign_key => 'owner_id'

看看:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Defining foreign key relationships for Rails' models