Polymorphism with Many-to-Many Associations – A Teach Me To Code Tutorial

by woody2shoes on June 3, 2011

Polymorphic associations are very simple, as are many-to-many associations. When you blend the two, it’s not nearly as simple. Since there isn’t a working build-in mechanism for many-to-many polymorphic associations.

Here’s a quick demo of what happens if you try to set up a traditional has_many :through association with a polymorphic association. I also show how to set things up so you can get the associated objects.

Download 101.3 MB
Download (iPod & iPhone) 45.5 MB

  • Guest

    Haven’t tried but try

      def items
        ….
      end

      def items.<<(item)
         ….
      end

    I think it should work.

  • Guest

    :( It doesn’t work

    • http://teachmetocode.com Charles Max Wood

      You may want to try having items return an ItemCollection object that responds to <<. Or try extending Array to track the collection object and call .items.create on the collection object.

  • Kittycharger

    We are an experienced group of internet sellers. All of our items are directly purchased by various reputable manufacturers throughout the world.
    http://www.fujifilm-battery-charger.co.uk/http://www.laptop-keyboard.org/http://www.keyboard-world.comhttp://www.samsung-battery-charger.co.uk/

  • http://www.facebook.com/gianluca.tessarolo Gianluca Tessarolo

    Hi, a little tip: you can avoid to exit and recall rails console simply calling: reload! into the console, try it and enjoy !

    • http://teachmetocode.com Charles Max Wood

      That’s true, but I’ve found that it doesn’t reload my objects properly. I suppose I could call ‘reload!’ and then simply re-initialize my objects.

  • sandeep koirala

    Well, I understand associations in rails. But, I am quite confused about where should many to many associations actually used. I think most of the associations fit one to many associations. I would really appreciate if you could clear these things for me.

    • http://teachmetocode.com Charles Max Wood

      You would use the many-to-many associations in situations where each object and be associated with many of the other. For example:

      Posts and Categories in a blog. (A category can have many posts. A post can have many categories.)
      Users and Roles in an authorized website. (A user can have many roles. A role can associate with many users.)
      Posts and Tags in a blog.
      Courses and Professors (Courses can be taught by different Professors. Professors can teach more than one Course.)

      Hope that helps.

Previous post:

Next post: