views:

25

answers:

2

I have a model as follows:

Campaign
  has_many :companies, :through => :contacts

There are many contacts with the same company. I just want one instance of each company.

I tried the following:

@campaign = Campaign.find(params[:id])
@companies = @campaign.companies

But this shows me all the companies for every contact I believe. At least that's what the output looks like.

How can I make sure that only a single instance of a company is added?

+4  A: 

When you use :through, it's usually useful to use the :uniq option, so you don't get repeated results

has_many :companies, :through => :contacts, :uniq => true
j.
sweet, never even seen that option before, thank you :)
Angela
+1  A: 

The currently-accepted solution by "j." will work, however it is very inefficient because it removed the duplicates in Ruby, instead of in SQL. It actually just runs .uniq! on the returned results.

The efficient and, in my opinion, proper way to do this is:

has_many :companies, :through => :contacts, :select => "DISTINCT companies.*"

It might not be as pretty, but it will get you what you want, will use no extra memory, and will be much faster.

bjeanes
interesting, I may give that a try....i much prefer keeping things in SQL
Angela