has_and_belongs_to_many or has_many :through?

As you may (or may not) know, there are two ways to build a many-to-many (or N-N) relationship with Rails.

  1. The first way uses has_and_belongs_to_many in both models. You’ll have to create a join table that has no corresponding model or primary key. ( ActiveRecord will look by default for a join table called groups_users )
  2. class Group < ActiveRecord::Base
    has_and_belongs_to_many :users # foreign keys in the join table
    end
    class User < ActiveRecord::Base
    has_and_belongs_to_many :groups # foreign keys in the join table
    end


    The join table can have more attributes which can be filled with the push_with_attributes method:

    class User < ActiveRecord::Base
    has_and_belongs_to_many :groups # foreign keys in the join table

    def join_group(group)
    groups.push_with_attributes(group, :joined_at => Time.now)
    end
    end

  3. The second way uses a has_many association with the :through option and a join model:
    class Subscriptions < ActiveRecord::Base
    belongs_to :group # foreign key - programmer_id
    belongs_to :user # foreign key - project_id
    end
    class Group :subscriptions
    end
    class User :subscriptions
    end

If you have to work with the relationship model as its own entity, thent you'll need to use has_many :through. Otherwise, you can just stick to has_and_belongs_to_many.

This entry was posted in Ruby on Rails and tagged , , . Bookmark the permalink.

4 Responses to has_and_belongs_to_many or has_many :through?

  1. gi says:

    Hell this post is unreadable.

  2. dude says:

    WTF! can a human read this?

  3. Taywin says:

    The display is unreadable because the poster didn’t put the code in a pre format block (could be a code tag or pre tag). As a result, the display ignores new line and the code part messes up the whole readability.

    Anyway, the post is not that helpful to me. What I am really looking for is a way to use and some examples of how to use in model, controller, and view. This post just shows how to use in model…

  4. Taywin says:

    The display is unreadable because the poster didn’t put the code in a pre format block (could be a code tag or pre tag). As a result, the display ignores new line and the code part messes up the whole readability.

    Anyway, the post is not that helpful to me. What I am really looking for is a way to use and some examples of how to use in model, controller, and view. This post just shows how to use in model…

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>