Reputation: 49
What is the correct way to create active record relationships for a scenario where-
One instance of a Model A can belong to multiple of instances of two other models, Model B and Model C at the same time.
Model B can only have one Model A.
Model C can have many Model A's.
An example is a job board where an employer is hiring for one position and candidate is applying and has many previous positions. I want both the candidate and employer positions to be from the same model.
Position Mode (Model A) can belong to both employers and candidates at the same time
Employer Model (Model B) has_one position
Candidate Model (Model C) has_many positions
Upvotes: 2
Views: 2197
Reputation: 458
Here's one way of accomplishing what you described in the question:
class Position < ActiveRecord::Base
belongs_to :candidate
belongs_to :employer
end
class Employer < ActiveRecord::Base
has_many :positions
end
class Candidate < ActiveRecord::Base
has_many :positions
ens
Note that a position can only belong to one employer and one candidate at a time; this is kind of nonsensical if you are creating a job board - the relationship between position and employer is probably correct, but candidates might have many applications, and an application would belong_to a position, while a position has_many applications. Or possibly also "favorites" so candidates could keep track of a list of positions to apply to.
The "theoretical" example that you started with:
Code:
class ModelA < ActiveRecord::Base
has_many :model_bs
has_many :model_c_relationships # join table!
has_many :model_cs, through: :model_c_relationships
end
class ModelB < ActiveRecord::Base
belongs_to :model_a
end
class ModelCRelationship < ActiveRecord::Base
belongs_to :model_a
belongs_to :model_c
end
class ModelC < ActiveRecord::Base
has_many :model_c_relationships
has_many :model_as, through: :model_c_relationships
end
If there is a situation where one type of object can belong to one other object, but that other object can be one of several types, then it might need a polymorphic association. For example, StackOverflow allows you to comment on both questions and answers. A comment can only belong to one comment-able parent object, therefore the code might look like this:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class Question < ActiveRecord::Base
has_many :comments, as: :commentable
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
has_many :comments, as: :commentable
end
Upvotes: 2