Search code examples
ruby-on-railsmodelhas-manyrelationships

Many-to-Many Relationships in Rails


I have two models I want to connect with an m-to-m relationship, but I want the relationship to have some data of its own, such as a date due or a count or something like that...

Suppose I have Users, Groups, and some UsersInGroups object, where users and groups both have a has_many X, :through Y relationship. UsersInGroups belongs_to a user and a group, but also has a join_date that shows when a user joined the group.

so I can use self.groups.A to get Group variables from User and vice versa, but how do I get at the join_date variable?


Solution

  • In a many to many relationship, if a User can have many groups, and you do aUser.user_in_groups, it will return an array of the groups (which will be an instance of the model class representing them). You can iterate over each of these and obtain the join_date on each one, or by indexing into the array: aUser.user_in_groups[0].join_date

    If you just want an array of join dates or something, I would look into the Ruby collect method.

    Iteration:

    aUser.users_in_groups.each do |group|
      group.join_date
    end