Question

I have a database with 2 tables; Users and Revisions. Revisions has multiple one-to-many relationships to the users table, for example created_by, verified_by, published_by (each field being a foreign key user id).

How would I go about defining this relationship in my Rails models?

Was it helpful?

Solution

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

Using these models:

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

You should probably change the association names to whatever makes most sense in your app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top