Rails不会回滚,也不会更新属性

时间:2019-10-14 15:37:57

标签: ruby-on-rails ruby

在终端中(后来我需要将其添加到迁移中),我想更新total_campaign_codes_amount,它代表每个信用活动的所有活动代码。该字段是一个counter_cache,要在终端中执行此操作,请输入以下脚本:

CreditCampaign.all.each do |cc|
  cc.update!(
    total_campaign_codes_amount: cc.campaign_codes.count
  )
end

我在sql中没有收到任何错误,一切正常,但是对于每个CreditCampaign显示0,这些值都不会保存到-total_campaign_codes_amount

  CreditCampaign Update (0.2ms)  UPDATE "credit_campaigns" SET "updated_at" = $1 WHERE "credit_campaigns"."id" = $2  [["updated_at", "2019-10-14 15:26:54.010779"], ["id", 1]]
   (0.4ms)  COMMIT
   (0.2ms)  SELECT COUNT(*) FROM "campaign_codes" WHERE "campaign_codes"."credit_campaign_id" = $1  [["credit_campaign_id", 2]]
   (0.1ms)  BEGIN
  CreditCampaign Update (0.2ms)  UPDATE "credit_campaigns" SET "updated_at" = $1 WHERE "credit_campaigns"."id" = $2  [["updated_at", "2019-10-14 15:26:54.013239"], ["id", 2]]
   (0.2ms)  COMMIT
 => [#<CreditCampaign id: 1, amount: 0.25e3, interest_rate: 0.12e2, installment_amount: 0.1e3, duration_in_months: 24, start_date: "2019-10-10", end_date: "2019-11-10", created_at: "2019-10-10 14:54:27", updated_at: "2019-10-14 15:26:54", name: "Credit Campaign #1", total_campaign_codes_amount: 15, used_campaign_codes_amount: 6>, #<CreditCampaign id: 2, amount: 0.1e1, interest_rate: 0.1e1, installment_amount: 0.1e1, duration_in_months: 1, start_date: "2011-01-01", end_date: "2020-01-01", created_at: "2019-10-14 13:40:02", updated_at: "2019-10-14 15:26:54", name: "test", total_campaign_codes_amount: 10, used_campaign_codes_amount: 0>]

我试图用update_attributes!代替update!,用find_each代替all.each,但是没有任何结果。

1 个答案:

答案 0 :(得分:1)

您无法更新Rails中的计数器缓存列,因为它已通过attr_readonly添加到包含模型的只读属性列表中。相反,您应该使用update_countersreset_counters