如何在 Rails 中使用 ActiveRecord 只获取一条记录而不是重复记录?
我有一个模型如下:
Campaign
has_many :companies, :through => :contacts
与同一家公司有很多联系人。我只想要每个公司的一个实例。
我尝试了以下操作:
@campaign = Campaign.find(params[:id])
@companies = @campaign.companies
但这向我显示了我相信的每个联系人的所有公司。至少输出看起来是这样的。
如何确保只添加一个公司实例?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用
:through
时,使用:uniq
选项通常很有用,这样您就不会得到重复的结果When you use
:through
, it's usually useful to use the:uniq
option, so you don't get repeated results“j”当前接受的解决方案。 可以工作,但是效率非常低,因为它删除了 Ruby 中的重复项,而不是 SQL 中的重复项。它实际上只是对返回的结果运行
.uniq!
。在我看来,有效且正确的方法是:
它可能不那么漂亮,但它会得到你想要的东西,不会使用额外的内存,而且会快得多。
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:
It might not be as pretty, but it will get you what you want, will use no extra memory, and will be much faster.