如何在 Rails 中使用 ActiveRecord 只获取一条记录而不是重复记录?

发布于 2024-09-14 17:53:03 字数 317 浏览 12 评论 0原文

我有一个模型如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半世蒼涼 2024-09-21 17:53:03

当您使用 :through 时,使用 :uniq 选项通常很有用,这样您就不会得到重复的结果

has_many :companies, :through => :contacts, :uniq => true

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
江湖彼岸 2024-09-21 17:53:03

“j”当前接受的解决方案。 可以工作,但是效率非常低,因为它删除了 Ruby 中的重复项,而不是 SQL 中的重复项。它实际上只是对返回的结果运行 .uniq!

在我看来,有效且正确的方法是:

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

它可能不那么漂亮,但它会得到你想要的东西,不会使用额外的内存,而且会快得多。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文