私は3つのモデルを持っています。雇用者、ユーザー、ジョブ。
class Employers
has_many :jobs
has_many :users, through: :jobs
end
class User
has_many :jobs
end
class Job
belongs_to :user
belongs_to :employer
end
Job モデルには、「current」という名前のブール列があります。雇用主のユーザー カウントは、「現在」とマークされたすべての関連ジョブをカウントすることによって得られます。
アクティブなレコードを使用するのではなく、独自のキャッシュ カウンターをロールすることにしました。
Job モデルで before フィルターを使用して、Employer モデルの users_count をインクリメントまたはデクリメントします。インクリメントは期待どおりに機能しますが、コードをどのように微調整しても...デクリメントはカウントを2の値で落とします.
これらのメソッドを少しクリーンアップできると確信しています...冗長性があるかもしれません。
1 デクリメントが 1 ではなく 2 を引くのはなぜですか?
2 アクティブ レコード キャッシュ カウンターは、このようなロジックを処理できますか?
class Job
before_destroy :change_employer_users_counter_cache_after_destroy
before_create :change_employer_users_counter_cache_after_create
before_update :change_employer_users_counter_cache_after_update
def change_employer_users_counter_cache_after_create
Operator.increment_counter(:users_count, self.operator_id) if self.current == true
end
def change_employer_users_counter_cache_after_update
if self.current_changed?
if self.current == true
Operator.increment_counter(:users_count, self.operator_id)
else
Operator.decrement_counter(:users_count, self.operator_id)
end
end
end
def change_employer_users_counter_cache_after_destroy
Operator.decrement_counter(:users_count, self.operator_id)
end
end