Has_many :through question

I have the following setup:

class Company < ActiveRecord::Base
has_many :company_groups
has_many :groups, :through => :company_groups
end

class CompanyGroup < ActiveRecord::Base
belongs_to :company
belongs_to :group
end

class Group < ActiveRecord::Base
belongs_to :group_type

has_many :company_groups
has_many :companies, :through => :company_groups
end

class GroupType < ActiveRecord::Base
has_many :groups
end

So a company is part of a group and there can be many types of groups.

Is it possible to get a list of distinct group types from the company?
i.e. company.group_types would return an array of the group types that
the particular company is in.

Let me know if you wish me to explain it a bit better

Thanks
Luke

In case anyone has the same problem I did it by using finder_sql:

class Company < ActiveRecord::Base
has_many :company_groups
has_many :groups, :through => :company_groups
has_many :group_types, :finder_sql => ‘SELECT DISTINCT gt.* FROM
group_types gt INNER JOIN groups g ON gt.id = g.group_type_id INNER JOIN
company_groups gc ON gc.group_id = g.id WHERE gc.company_id = #{id}’
end

I’m sure there must be a cleaner way of doing it though…

Cheers
Luke

According to my book (agile web development with rails 2nd ed)…

class Company < ActiveRecord::Base
has_many :company_groups
has_many :groups, :through => :company_groups
has_many :groups_types, :through => :company_groups, :unique =>
true
end

or

class Company < ActiveRecord::Base
has_many :company_groups
has_many :groups, :through => :company_groups
has_many :groups_types, :through => :company_groups, :select =>
“distinct groups.*”
end

Sorry about the timing, this group is too large to read daily.
On Mar 27, 9:10 pm, Luke P. [email protected]

reed wrote:

According to my book (agile web development with rails 2nd ed)…

class Company < ActiveRecord::Base
has_many :company_groups
has_many :groups, :through => :company_groups
has_many :groups_types, :through => :company_groups, :unique =>
true
end

or

class Company < ActiveRecord::Base
has_many :company_groups
has_many :groups, :through => :company_groups
has_many :groups_types, :through => :company_groups, :select =>
“distinct groups.*”
end

Sorry about the timing, this group is too large to read daily.
On Mar 27, 9:10 pm, Luke P. [email protected]

Thanks, I not sure thats what I was after though.

I’m after a unique set of group types not groups.

e.g.

groups table:

id group_type_id name

1 1 a
2 1 b
3 2 x
4 2 y

A company in groups b & x should return group_types with ids [1,2] and a
company in groups a & b should return a group_type with id [1].

Good lord, I think it’s too large/active to +skip+ a day!

RSL