Has_many :through

Hi
I have the models
1.Group
has_many :user_groups
has_many :contacts, :through => :user_groups
2.Contacts
has_many :user_groups
has_many :groups, :through => :user_groups
3.UserGroup
belongs_to :group
belongs_to :contact

     Now i have a group_id.I have to find the contact (he is the

manager (group_user_type_id=4 in user_groups)…How can I do that?

Thanks in advance
Sijo

Sijo Kg wrote:

Hi
I have the models
1.Group
has_many :user_groups
has_many :contacts, :through => :user_groups
2.Contacts
has_many :user_groups
has_many :groups, :through => :user_groups
3.UserGroup
belongs_to :group
belongs_to :contact

     Now i have a group_id.I have to find the contact (he is the

manager (group_user_type_id=4 in user_groups)…How can I do that?

Thanks in advance
Sijo

Unless you are recording other information about the relationship
between Groups and Contacts, then an HABTM relationship is probably a
better fit:

class Group
has_and_belongs_to_many :contacts
end

class Contact
has_and_belongs_to_many :groups
end

and create your join table (don’t forget to drop the id column).

Then you can do things like:

Group.find(:first).contacts -> Returns an array of Contacts belonging
to that group

Hi
Thanks for your reply.Here in junction table user_groups I have the
additionl storing like
id integer not null default nextval(‘user_groups_id_seq’::regclass)
contact_id | integer |
group_id | integer |
group_user_type_id | integer |

Sijo

Sijo Kg wrote:

Hi
Thanks for your reply.Here in junction table user_groups I have the
additionl storing like
id integer not null default nextval(‘user_groups_id_seq’::regclass)
contact_id | integer |
group_id | integer |
group_user_type_id | integer |

Sijo

Ahhh - I see. You are not only recording the contacts belonging to a
group, but also different kinds of groups.

May I suggest you actually create another model to handle group_types,
something like this:

class Contact
has_and_belongs_to_many :groups
has_many :grouptypes, :through => :groups
end

class Group
has_and_belongs_to_many :contacts
belongs_to :grouptype
end

class GroupType

Has a text field called “name”

has_many :groups
has_many :contacts, :through => :groups
end

Grouptype.find_by_name(“Manager”).contacts

etc.

Am I on the right track here?