Rails:为现有has_many记录创建/更新has_many关系

时间:2019-03-07 12:52:54

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

给出:

$months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

$monthlySales = Sale::whereIn(DB::raw('MONTH(created_at)'), $months)
                    ->whereYear('created_at', '=', date('Y'))
                    ->select(DB::raw("SUM(((sellingprice * discount_percent) / 100) * productqty) as monthlySale"))
                    ->get();

dd($monthlySales);

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

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

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

还有其他人遇到吗?我认为一种解决此问题的方法是在save!内使用类似_existing: true的键(很像customers_attributes用于使外键无效)可以工作。还是类似的东西违反了我没有看到的Rails原理?

1 个答案:

答案 0 :(得分:1)

实际上,您不需要为此使用嵌套属性,而可以直接设置association_ids属性:

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

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