【问题标题】:In Rails 5 what is the best way to show duplicate records across a has_and_belongs_to_many and a belongs to relationship在 Rails 5 中,跨 has_and_belongs_to_many 和属于关系显示重复记录的最佳方法是什么
【发布时间】:2017-02-21 16:03:34
【问题描述】:

给定以下模型结构;

class Project < ApplicationRecord
  has_many :leads
  has_and_belonds_to_many :clients
end

class Lead < ApplicationRecord
  belongs_to :project
end

class Client < ApplicationRecord
  has_and_belongs_to_many :projects
end

您如何建议通过 Client 报告重复的潜在客户?

现在我正在用扁平化和计数做一些非常粗糙的事情,感觉应该有一个“Ruby方式”。

理想情况下,我希望界面能够说出Client.first.duplicate_leadsLead.first.duplicate?

当前(糟糕的)解决方案

@duplicate_leads = Client.all.map(&:duplicate_leads).flatten

Class Client
  def duplicate_leads
    leads = projects.includes(:leads).map(&:leads).flatten
    grouped_leads = leads.group_by(&:email)
    grouped_leads.select { |_, v| v.size > 1 }.map { |a| a[1][0] }.flatten
  end
end

环境

  • 导轨 5
  • Ruby 2.3.1

【问题讨论】:

标签: ruby-on-rails ruby activerecord


【解决方案1】:

你可以试试这个。

class Client < ApplicationRecord
  has_and_belongs_to_many :projects
  has_many :leads, through: :projects

  def duplicate_leads
    duplicate_ids = leads.group(:email).having("count(email) > 1").count.keys
    Lead.where(id: duplicate_ids)
  end
end

【讨论】:

    【解决方案2】:

    您可以尝试创建从 Lead 通过 Project 回到 Lead 的 has_many 关联,在该关联中,您使用 lambda 根据两个记录之间的电子邮件匹配和不匹配的 id 动态加入。这会将两条记录标记为重复 - 如果您只想标记一条,则可以要求一条的 id 小于另一条的 id。

    一些提示:Rails has_many with dynamic conditions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2011-04-25
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      相关资源
      最近更新 更多