gpt4 book ai didi

ruby-on-rails - rails 4 : counter_cache in has_many :through association with dependent: :destroy

转载 作者:行者123 更新时间:2023-12-04 05:54:05 28 4
gpt4 key购买 nike

虽然已经有人问过类似的问题:

  • counter_cache with has_many :through
  • dependent => destroy on a "has_many through" association
  • has_many :through with counter_cache

  • 他们都没有真正解决我的问题。

    我有三个模型,有一个 has_many :through 关联:
    class User < ActiveRecord::Base
    has_many :administrations
    has_many :calendars, through: :administrations
    end

    class Calendar < ActiveRecord::Base
    has_many :administrations
    has_many :users, through: :administrations
    end

    class Administration < ActiveRecord::Base
    belongs_to :user
    belongs_to :calendar
    end

    联接管理模型具有以下属性:
    id
    user_id
    calendar_id
    role

    我要数多少 calendars每个 user有多少 users每个 calendar已。

    我打算使用 counter_cache 如下:
    class Administration < ActiveRecord::Base
    belongs_to :user, counter_cache: :count_of_calendars
    belongs_to :calendar, counter_cache: :count_of_users
    end

    (当然,还有将 :count_of_calendars 添加到 users 表和 :count_of_userscalendars 表的相应迁移。)

    但是后来,我偶然发现了 this warning in Rails Guides :

    4.1.2.4 :dependent

    If you set the :dependent option to:

    • :destroy, when the object is destroyed, destroy will be called on its associated objects.
    • :delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.

    You should not specify this option on a belongs_to association that is connected with a has_many association on the other class. Doing so can lead to orphaned records in your database.



    因此,计算多少 calendars 是一个好习惯。每个 user有多少 users每个 calendar已?

    最佳答案

    那么,dependent: :destroy将销毁关联的记录,但不会更新 counter_cache ,因此您可能在 counter_cache 中计数错误.相反,您可以实现一个回调来销毁关联的记录,并更新您的 counter_cache .

    class Calendar < ActiveRecord::Base

    has_many :administrations
    has_many :users, through: :administrations


    before_destroy :delete_dependents

    private
    def delete_dependents
    user_ids = self.user_ids
    User.delete_all(:calendar_id => self.id)
    user_ids.each do |u_id|
    Calendar.reset_counters u_id, :users
    end
    end
    end

    同样,为 User 实现此操作模型也是

    关于ruby-on-rails - rails 4 : counter_cache in has_many :through association with dependent: :destroy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32275640/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com