我有一个包含2个表的数据库;用户和修订。修订版与users表有多个一对多关系,例如created_by,verified_by,published_by(每个字段都是外键用户ID)。
我如何在Rails模型中定义这种关系?
答案 0 :(得分: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.
您可能应该将关联名称更改为应用中最有意义的内容。