开发者

How can I just get one record instead of duplicates using ActiveRecord in Rails?

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 mak开发者_如何学Goe sure that only a single instance of a company is added?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜