Search code examples
ruby-on-railsrubyruby-on-rails-5associationspolymorphic-associations

Ruby on rails polymorphic associations


Is there a difference between the has_many , has_and_belongs_to_many and the polymorphic association. Why should I use polymorphic association.


Solution

  • has_many, has_and_belongs_to_many and the polymorphic associations are solutions to different problems.

    • has_many means you have a parent object that has many other children. While the children do only belong to that specific parent.
    • has_and_belongs_to_many means the objects are not structured in a hierarchical structure. And that the objects on both sides can be connected to mutiple others. A good example is probably a tagging system. A thing can be tagged with multiple tags. But the tags do not only belong to one thing, they can be added to other things too.
    • polymorphic associations are used when the association doesn't point to one specific other model. An example might be an Author model that has a created_work association, but it doesn't point to a decicated CreatedWork model. But instead, it can return different things, like an instance of a Book, a Play an Article, or a simple Comment which are all different classes and have different database tables.