简体   繁体   中英

Rails don't rollback and don't update attribute either

In the terminal (later I need to add this to the migration) I want to update total_campaign_codes_amount which represents all campaign codes for each credit campaign. This field is a counter_cache and to do so in terminal I've got this script:

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

I didn't received any errors in my sql, everything should worked but these values are not saved to - total_campaign_codes_amount for each CreditCampaign shows 0.

  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>]

I was trying to use update_attributes! instead of update! and find_each instead of all.each but without any results.

You can not update counter cache column in Rails, because it is added to the containing model's list of read-only attributes through attr_readonly . Instead you should use update_counters or reset_counters .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM