我有兩個類Ad
s和Zone
s,它們都從一個叫做Tracked
的類繼承而來,它又包含幾個Event
s。這個想法是Ad
以及Zone
可以與各種事件(即'查看','點擊','轉換')相關聯。這些事件必須被追蹤。Rails模型複雜繼承協會
我該怎麼去模擬使用ActiveRecord
s?遷移代碼的外觀如何?
這是我走到這一步:
事件:
class Event < ActiveRecord :: Base
attribute :event_date
belongs_to :trackable, polymorphic: true
[...]
end
跟蹤:
class Tracked < ActiveRecord :: Base
self.abstract_class = true
has_many :views, class_name: "Event"
has_many :clicks, class_name: "Event"
has_many :conversions, class_name: "Event"
belongs_to :trackable, polymorphic: true
[...]
end
廣告:
class Ad < Tracked
attribute :size, :content
attr_accessor :width, :height
belongs_to :advertisers
has_and_belongs_to_many :campaigns
[...]
end
活動:
require 'date'
class Campaign < ActiveRecord :: Base
attribute :name, :target_url,
:expiration_date,:categories,
:billing_type, :budget, :budget_type,
:cp_click, :cp_view, :cp_conversion
belongs_to :advertiser
has_and_belongs_to_many :ads
has_many :zones
[...]
end
起初我還以爲我可能要使用through
關聯,但因爲它是最重要的,我要區分這三個事件(查看,點擊,轉換)我認爲我可以'應用這種模式。所以我想我得用Polymorphic Associations
。
請注意,我粘貼的代碼包含創建模型的所有必要信息,即沒有我遺漏的屬性或關聯。另外我知道如何爲所有不屬於上述問題的屬性/關聯編寫遷移代碼。
好主意!我真的忘了我可以分離數據模型和可跟蹤的邏輯。 – Nessuno