1

我有一个有 2 个表的数据库;用户和修订。Revisions 与 users 表有多个一对多的关系,例如 created_by、verified_by、published_by(每个字段都是外键用户 ID)。

我将如何在我的 Rails 模型中定义这种关系?

4

1 回答 1

4
class Revision < ActiveRecord::Base
  belongs_to :creator, :foreign_key => "created_by", :class_name => "User"
  belongs_to :verifier, :foreign_key => "verified_by", :class_name => "User"
  belongs_to :publisher, :foreign_key => "published_by", :class_name => "User"
end

class User < ActiveRecord::Base
  has_many :creations, :foreign_key => "created_by", :class_name => "Revision"
  has_many :verifications, :foreign_key => "verified_by",
    :class_name => "Revision"
  has_many :publications, :foreign_key => "published_by",
    :class_name => "Revision"
end

使用这些模型:

User.first.creations    #=> [#<Revision>, #<Revision>, ...]
Revision.first.creator  #=>  #<User>
# ...etc., for verifier/verifications and publisher/publications.

您可能应该将关联名称更改为在您的应用中最有意义的名称。

于 2010-01-13T11:40:54.120 回答