同様の質問がすでに尋ねられていますが:
実際に私の問題に対処するものはありません。
has_many :through Association を持つ 3 つのモデルがあります。
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_users
calendars
しかし、その後、Rails Guides で次の警告に出くわしました。
4.1.2.4 :依存
:dependent オプションを次のように設定した場合:
- :destroy、オブジェクトが破棄されると、関連付けられたオブジェクトに対して destroy が呼び出されます。
- :delete、オブジェクトが破棄されると、関連するすべてのオブジェクトが、destroy メソッドを呼び出さずにデータベースから直接削除されます。
このオプションは、他のクラスの has_many アソシエーションに接続されている属しているアソシエーションでは指定しないでください。これを行うと、データベース内のレコードが孤立する可能性があります。
したがって、それぞれが持っている数と、calendars
それぞれuser
が持っている数を数える良い習慣は何でしょうか?users
calendar