Has_many_through inheritance

Hi all!

In my application I’m trying to create a model (Groups), which will
allow me to save groups of objects from various tables under a common
name. For example, one record in this table could refer to a group of
users. Another could refer to a group of photos. How should I do this?
When I use has_many_through I have to specify the group_id as well as
the id for whatever object I am referring to. But if the other id could
refer to a photo, or a user, or another model, how do I setup this kind
of inheritance? Do I have multiple foreign key fields in the table that
links the two together? EX: group_id, user_id, photo_id etc. and leave
the fields not being used blank. Or does this cause an error because
they are indexes?

Best,
Ben

Ben V. wrote:

Hi all!

In my application I’m trying to create a model (Groups), which will
allow me to save groups of objects from various tables under a common
name. For example, one record in this table could refer to a group of
users. Another could refer to a group of photos. How should I do this?
When I use has_many_through I have to specify the group_id as well as
the id for whatever object I am referring to. But if the other id could
refer to a photo, or a user, or another model, how do I setup this kind
of inheritance? Do I have multiple foreign key fields in the table that
links the two together? EX: group_id, user_id, photo_id etc. and leave
the fields not being used blank. Or does this cause an error because
they are indexes?

Best,
Ben

  1. You should name the model like Group, not Groups
  2. You should look for :polymorphic => true, somewhere like this:
    http://railscasts.com/episodes/154-polymorphic-association
    Active Record Associations — Ruby on Rails Guides

or just type in Google “polymorphic association Rails”, like this
http://www.google.com.ua/search?hl=uk&client=firefox-a&rls=org.mozilla:en-US:official&hs=8kT&ei=z9lFSsb0MMG1sgby4MEM&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=polymorphic+association+Rails&spell=1