我对Rails相当陌生,我很想知道一些正确的方向。我理解科技创新的利弊。
使用Rails 3.2中单个表继承和多态关联的组合来建模AR-关系的最佳实践是什么?通过决定同时使用这两种方法,这个应用程序会有什么重要的缺点吗?Rails 4会改变什么吗?
到目前为止,我有以下几种型号:
class Course
has_many :participants, class_name: 'User'
has_many :events, as: :eventable
end
class User
has_many :events, as: :eventable
has_many :courses
end
class Resource
has_many :events, as: :eventable
end
class Subject < Resource
end
class Location < Resource
end
class Medium < Resource
end
class Event
belongs_to :eventable, polymorphic: true
end到目前为止,看起来相对容易,但我正在与复杂的联系进行斗争。如何设置以下与STI的关联?
我想从数据库中检索的示例
蒂亚和最诚挚的问候
克里斯
发布于 2013-06-25 14:06:36
您可以使用这些,以及更多Rails的魔力:)
class Course
has_many :participants, class_name: 'User'
has_many :subjects, conditions: ['type = ?', 'Subject']
has_many :locations, conditions: ['type = ?', 'Location']
has_many :events, as: :eventable
end
class User
has_many :subjects, conditions: ['type = ?', 'Subject']
has_many :locations, conditions: ['type = ?', 'Location']
has_many :events, as: :eventable
belongs_to :event, foreign_key: :teacher_id
end
class Resource
has_many :contacts, class_name: 'User'
has_many :events, as: :eventable
end
class Event
belongs_to :eventable, polymorphic: true
has_many :teachers, class_name: 'User'
has_many :subjects, conditions: ['type = ?', 'Subject']
has_many :locations, conditions: ['type = ?', 'Location']
has_many :media, conditions: ['type = ?', 'Medium']
end我认为这涵盖了您所有的用例。
注意:您可能应该将您的模型从Media重命名为Medium,因为Rails在奇异化的模型名称中工作得更好,如果不这样做,您可能会遇到一些问题。
https://stackoverflow.com/questions/17298471
复制相似问题