【发布时间】:2014-01-14 22:25:16
【问题描述】:
我有两个类Ads 和Zones,它们都继承自一个名为Tracked 的类,而后者又包含几个Events。这个想法是Ads 和Zones 可以与各种事件相关联(即“查看”、“点击”、“转化”)。必须跟踪这些事件。
我将如何使用ActiveRecords 进行建模?迁移代码是什么样的?
这是我目前得到的:
事件:
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。
请注意,我粘贴的代码包含创建模型所需的所有信息,即我没有遗漏任何属性或关联。我也知道如何为不属于上述问题的所有属性/关联编写迁移代码。
【问题讨论】:
标签: ruby-on-rails activerecord migration polymorphic-associations