Paul Byrne
Paul Byrne

Reputation: 1615

Model that belongs to one of two parents

I'm trying to decide on the best relationship structure for three models I have in a Rails app.

The models are candidate, an employer, and a video.

Sometimes a video will belong to an employer, other times a candidate. Because of this I am loathe to put foreign keys for both employer and candidate on a video, because it feels wrong that one will always be nil.

The problem with the code below is that the video will not have many candidates, but I can't do a through relationship with belongs_to. What is a better way?

class Video < ActiveRecord::Base
  has_many :video_candidates
  has_many :candidates, :through => :video_candidates
end

class Candidate < ActiveRecord::Base
  has_many :video_candidates
  has_many :videos, :through => :video_candidates
end

class VideoCandidate < ActiveRecord::Base
  belongs_to :candidate
  belongs_to :vieo
end

Edit: Polymorphic association is the way to go. I'm going to put my solution below. Hope this helps someone.

class Video < ActiveRecord
    belongs_to :watchable, polymorphic: true
end

class Candidate < ActiveRecord::Base
    has_many :videos, as: :watchable
end

class Employer < ActiveRecord::Base
    has_many :videos, as: :watchable
end

And the migration

class CreateVideos < ActiveRecord::Migration[5.0]
  def change
    create_table :videos do |t|
      t.string :title
      t.belongs_to :watchable, polymorphic: true

      t.timestamps
    end
    add_index :videos, [:watchable_id, :watchable_type]
  end
end

Upvotes: 0

Views: 53

Answers (1)

dp7
dp7

Reputation: 6749

This is an ideal case to go for polymorphic association

Also refer Railscast episode

Upvotes: 1

Related Questions