【问题标题】:Rails: Creating/updating has_many relationships for existing has_many recordsRails:为现有的 has_many 记录创建/更新 has_many 关系
【发布时间】:2019-03-07 12:52:53
【问题描述】:

给定:

class Group < ApplicationRecord
  has_many :customers, inverse_of: :group
  accepts_nested_attributes_for :customers, allow_destroy: true
end

class Customer < ApplicationRecord
  belongs_to :group, inverse_of: :customers
end

我想创建/更新一个组并将现有客户分配给该组,例如:

Group.new(customers_attributes: [{ id: 1 }, { id: 2 }])

但这不起作用,因为 Rails 只会抛出 ActiveRecord::RecordNotFound: Couldn't find Customer with ID=1 for Group with ID=(或 ID=the_group_id,如果我正在更新 Group)。我发现修复它的唯一方法是提取customers_attributes,然后在Groupsave! 调用之后执行单独的Customer.where(id: [1,2]).update_all(group_id: 'groups_id')

还有其他人遇到过这个吗?我觉得解决它的一种方法是在customers_attributes 内有一个像_existing: true 这样的键(很像_destroy: true 用于使外键无效)可以工作。或者这样的事情是否违反了我没有看到的 Rails 原则?

【问题讨论】:

    标签: ruby-on-rails ruby has-many


    【解决方案1】:

    其实这个不用嵌套属性,直接设置association_ids属性即可:

    Group.new(customer_ids: [1, 2])
    

    这将在保存记录时自动更新每个引用客户的 group_id。

    【讨论】:

    • 啊,我忘了说。因此,虽然这对于创建新组很好,但如果您在更新组时这样做,它会删除可能已附加到该 Group 的任何以前的客户。我正在寻找一种一体化解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多