开发者

Rails transparent child relationship

开发者 https://www.devze.com 2023-02-24 10:31 出处:网络
I have a polymorphic relationship, and I would like the child (polymorph?) to be completely transparent.The setup is generic:

I have a polymorphic relationship, and I would like the child (polymorph?) to be completely transparent. The setup is generic:

class ScheduledEvent < ActiveRecord::Base
    belongs_to :schedule开发者_JAVA百科able, 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

I would like to be able to treat AppointmentTypeOne and AppointmentTypeTwo as if THEY had the #starts_at and #ends_at table columns.

Method-wise it's very easy to add #starts_at, #starts_at=, etc to my AppointmentX classes, and refere back to ScheduledEvent. But how can I setup so that the relationship is transparent to ActiveRelation also? Letting me do something like:

AppointmentTypeOne.where('starts_at IS NOT NULL')

(not having to join or include :scheduled_event)


It sounds like you want to use Single Table Inheritance, not a has_one association. That will allow you to create subclasses of ScheduledEvent for each appointment type:

class ScheduledEvent < ActiveRecord::Base

end

class AppointmentTypeOne < ScheduledEvent

end

class AppointmentTypeTwo < ScheduledEvent

end

Basically, you add a type column to your scheduled_events table, and rails takes care of the rest.

This forum post covers all of the details: http://railsforum.com/viewtopic.php?id=3815

0

精彩评论

暂无评论...
验证码 换一张
取 消