Rails透明的孩子关系

时间:2011-04-13 00:27:01

标签: ruby-on-rails activerecord polymorphic-associations

我有多态关系,我希望孩子(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

我希望能够将AppointmentTypeOneAppointmentTypeTwo视为具有#starts_at#ends_at表格列。

按方法,将#starts_at#starts_at=等添加到我的AppointmentX类非常容易,并引用回ScheduledEvent。但是我如何设置以使关系对ActiveRelation也是透明的呢?让我做一些像:

AppointmentTypeOne.where('starts_at IS NOT NULL')

(不必joininclude :scheduled_event

1 个答案:

答案 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