开发者

What's the difference between polymorphic and write several one-to-many association

开发者 https://www.devze.com 2023-01-29 20:14 出处:网络
Hey guys, I\'m new to rails here ar开发者_运维问答e the 2 ways of making a Drummer model and Cymbal model both have many videos

Hey guys, I'm new to rails here ar开发者_运维问答e the 2 ways of making a Drummer model and Cymbal model both have many videos

1st way by using polymorphic:

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

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

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

2nd way by using two 1:m association:

class Drummer < ActiveRecord::Base has_many :videos end

class Cymbal < ActiveRecord::Base has_many :videos, end

class Video < ActiveRecord::Base belongs_to :drummer belongs_to :cymbal end

I haven't try them in console, But I think both will work as they should. But I don't know the difference?


I believe that you must use polymorphic method because a model cannot belongs_to (one to one association) more than one other model. For more info see this rails guide: http://guides.rubyonrails.org/association_basics.html


It depends on the columns you have in your database. If you have videoable_type and videoable_id you're doing polymorphism. In that case, calling videoable on an instance of Video can return anything, it's not related to drummers or cymbals. If it is drummer_id and cymbal_id it's the latter version you described.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号