0
레일스 앱에서 사용하는 세 가지 모델에 대한 최상의 관계 구조를 결정하려고합니다.두 부모 중 하나에 속하는 모델
모델은 후보, 고용주 및 비디오입니다.
때때로 비디오는 고용주에 속하며, 다른 경우에는 후보자입니다. 이 때문에 나는 고용주와 후보자 모두에게 외래 키를 비디오에 넣는 것을 꺼리는데, 이는 항상 잘못된 것이라고 느끼기 때문입니다.
아래 코드의 문제점은 비디오가 이 아닌에 많은 후보가 있지만 belongs_to와 (과)의 관계를 통해 수행 할 수 없다는 것입니다. 더 좋은 방법은 무엇입니까?
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
편집 : 다형성 연관성이 있습니다. 아래에 내 솔루션을 넣을 것입니다. 희망이 사람을 도움이됩니다.
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
그리고 마이그레이션
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