【问题标题】:Rails - destroy a 'join table' association whereRails - 销毁“连接表”关联,其中
【发布时间】:2015-10-14 12:29:07
【问题描述】:

我想知道在给定条件的情况下,是否有一种 Rails 方法可以破坏 has_many 关联。 买家

class Buyer < ActiveRecord::Base
  has_many :phones, as: :phoneable, dependent: :destroy, class_name: 'Telephone'
end

电话

class Telephone < ActiveRecord::Base
  belongs_to :phoneable, polymorphic: true
end

我想加入带有电话的买家并销毁所有电话where('buyers.tel = telephones.number')。编写此查询的最佳方式是什么?

【问题讨论】:

  • 如果表当前不存在,我建议创建一个迁移来创建连接表。然后编写一个 rake 任务来填充它。

标签: ruby-on-rails ruby-on-rails-4 activerecord


【解决方案1】:

如果您只处理 1 个Buyer 记录:

buyer = Buyer.first
buyer.phones.where('number = ?', buyer.tel).destroy_all

如果对所有Buyers

# XXX this will select all buyers you want but in your case you want to destroy the phones not the buyers so we need the reverse one check next:
Buyer.joins(:phones).where("buyers.tel = telephones.number")

# but this one will as we need the reverse relation:
Telephone.where("phoneable_type = 'Buyer' and buyers.tel = telephones.number").includes(:phoneable)

请注意,我们添加了一个条件 phoneable_type = 'Buyer',因为您具有多态关系,并且您只需要为 Buyer 创建的条件

【讨论】:

  • 这意味着我必须为买家中的每条记录运行查询。有没有办法在单个连接查询中做到这一点?
  • @leemour 检查与 1 个买家合作并与所有买家合作的更新答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多