我有多态关系,我希望孩子(polymorph?)完全透明。设置是通用的:
class ScheduledEvent < ActiveRecord::Base
belongs_to :scheduleable, polymorphic:true
#has column names like #starts_at, #ends_at
end
class AppointmentTypeOne < ActiveRecord::Base
has_one :scheduled_event, :as=>:scheduleable, :dependent=>:destroy
end
class AppointmentTypeTwo < ActiveRecord::Base
has_one :scheduled_event, :as=>:scheduleable, :dependent=>:destroy
end
我希望能够将AppointmentTypeOne
和AppointmentTypeTwo
视为具有#starts_at
和#ends_at
表格列。
按方法,将#starts_at
,#starts_at=
等添加到我的AppointmentX
类非常容易,并引用回ScheduledEvent
。但是我如何设置以使关系对ActiveRelation
也是透明的呢?让我做一些像:
AppointmentTypeOne.where('starts_at IS NOT NULL')
(不必join
或include
:scheduled_event
)
答案 0 :(得分:0)
听起来您想使用单表继承,而不是has_one关联。这将允许您为每个约会类型创建ScheduledEvent
的子类:
class ScheduledEvent < ActiveRecord::Base
end
class AppointmentTypeOne < ScheduledEvent
end
class AppointmentTypeTwo < ScheduledEvent
end
基本上,您将一个类型列添加到scheduled_events表中,rails将负责其余的事务。
此论坛帖子涵盖了所有细节:http://railsforum.com/viewtopic.php?id=3815