views:

37

answers:

1

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?

+1  A: 

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
Zachary
Collect is almost what I'm looking for, thanks! One more thing -- what if I have aUser and aGroup and I want to find the join date from those two?
Loyal Tingley
since usersingroups belongs to both models, you can call "users_in_groups" on each of them, and get an array of those object, which will all have a join_date.
Zachary
So, find UsersInGroups with the constraint `:user_id => aUser.id, :group_id => aGroup.id`? Seems like it's working okay, thanks :)
Loyal Tingley