The question of the use of polymorphic association in rails

As guys I'm new to rails, here is my code:

class Video < ActiveRecord::Base
  belongs_to :videoable, :polymorphic => true
end

class Drummer < ActiveRecord::Base
  has_many :videos,:as => :videoable
end


class Cymbal < ActiveRecord::Base
  has_many :videos, :as => :videoable
end

From this point of view, I can use drummer.videosto get the whole video that belongs to the drummer, But I can not use video.drummer to find out who the video belongs to.

Of course, I can use video.where (: videoable_id => '1' ,: videoable_type => 'drummer') to find the exact drummer record, but I think it should be elegant to do it on the rails, right?

and one more question, I want to improve this association, video and drummer, video and cymbal should be many-to-many, sometimes there is more than one drummer or 1 cymbal in one video, so it makes sense to do it here. How can i do this?

+3
3

" ", ( ), :

belongs_to :drummer, :class_name => "Drummer", :foreign_key => "videoable_id"
belongs_to :cymbal, :class_name => "Cymbal", :foreign_key => "videoable_id"

Rails , , .

+1

Drummer Cymbal , STI . type, , has_many, :

class Subject < ActiveRecord::Base
  has_many :subject_videos, :dependent => :destroy
  has_many :videos, :through => :subject_videos
end

class Drummer < Subject
end

class Cymbal < Subject
end

SubjectVideo subject_id video_id. :

class Video < ActiveRecord::Base
  has_many :subject_videos, :dependent => :destroy
  has_many :subjects, :through => :subject_videos
end

"--".

d = Drummer.create
d.videos # []
d.videos.create(:name=>"Stompin' at the Savoy")
v = Video.find_by_name("Stompin' at the Savoy")
v.subjects # [Drummer]

The main drawback of this approach is that Drummer and Cymbal are now stored in the same table, which may be undesirable if they have multiple columns.

If you still need to use many-to-many relationships using polymorphism, see also has_many_polymorphs .

+1
source

Source: https://habr.com/ru/post/1780487/


All Articles