レールで ahoy を使用してモデルを追跡する方法
概要
アホイをうまく統合しました。しかし、私の目的は、モデルの展示ページが何回アクセスされたかを追跡することです。
CarModel と CarMake の 2 つのモデルがあるとします。 CarModel.first.visits や CarMake.first.visits などの訪問をトラクトしたい
しかし、唯一の解決策は、 ahot.track(“model”+car_model.id) をヒットしてイベントに保存し、文字列でクエリする必要がありますが、これは一般的な方法ではありません。
Model.visits で任意のモデルの訪問を取得したい アホイサポートってこんな感じですか?
解決策
ここでは CarModel の Model.visits を実現するためのソリューションを示します。他のモデルでも同じことが可能です。
rails g migration CreateCarModelVisits car_model:references visit:references
それを Ahoy Visit テーブルに関連付けます (Ahoy の移行に注意してください)。
class CreateVisitable < ActiveRecord::Migration[6.1]
def change
create_table :visitables do |t|
t.references :car_model, foreign_key: true
t.references :visit, foreign_key: { to_table: :ahoy_visits }
t.timestamps
end
end
end
1 対多の関連付けを実装できます。Ahoy テーブルの変更を避けるために、私は単純に多対多の関係を作成しています。
class CarModel < ApplicationRecord
has_many :visitables, dependent: :destroy
has_many :visits, through: :visitables, class_name: 'Ahoy::Visit'
end
class Visitable < ApplicationRecord
belongs_to :car_model
belongs_to :visit, class_name: 'Ahoy::Visit'
end
class Ahoy::Visit < ApplicationRecord
has_many :visitables, dependent: :destroy
has_many :car_models, through: :visitables
end
これは、任意のコントローラー/モデル コールバックを介して実行できます。コントローラーのコールバックの場合:
CarModel.first.visits << current_visit
CarModel.first.visits