【问题标题】:Rails transparent child relationshipRails 透明子关系
【发布时间】:2011-04-13 00:27:01
【问题描述】:

我有一个多态关系,我希望孩子(多态?)是完全透明的。设置是通用的:

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

【问题讨论】:

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


    【解决方案1】:

    听起来您想使用单表继承,而不是 has_one 关联。这将允许您为每个约会类型创建 ScheduledEvent 的子类:

    class ScheduledEvent < ActiveRecord::Base
    
    end
    
    class AppointmentTypeOne < ScheduledEvent
    
    end
    
    class AppointmentTypeTwo < ScheduledEvent
    
    end
    

    基本上,您向 schedule_events 表添加一个类型列,其余的由 rails 处理。

    此论坛帖子涵盖了所有详细信息:http://railsforum.com/viewtopic.php?id=3815

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      相关资源
      最近更新 更多