首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与复杂的Rails activerecord关联和连接模型进行斗争

与复杂的Rails activerecord关联和连接模型进行斗争
EN

Stack Overflow用户
提问于 2013-06-25 13:19:13
回答 1查看 649关注 0票数 0

我对Rails相当陌生,我很想知道一些正确的方向。我理解科技创新的利弊。

使用Rails 3.2中单个表继承和多态关联的组合来建模AR-关系的最佳实践是什么?通过决定同时使用这两种方法,这个应用程序会有什么重要的缺点吗?Rails 4会改变什么吗?

到目前为止,我有以下几种型号:

代码语言:javascript
复制
    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的关联?

  • 一门课程可以有许多资源(作为科目/地点)
  • 用户可以拥有许多资源(作为主题/位置)
  • 资源可以有许多用户(作为联系人)
  • 事件本身可以有其他用户(作为教师)。
  • 事件本身可以有额外的资源(作为位置/主题/媒体)

我想从数据库中检索的示例

  • 用户的所有事件
  • 一门课程的所有项目
  • 参与者的所有组合事件(用户和课程)
  • 事件中的所有类型位置的关联资源
  • 所有来自活动的相关教师
  • 课程中的所有类型位置资源
  • 用户提供的所有类型的主题资源

蒂亚和最诚挚的问候

克里斯

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-25 14:06:36

您可以使用这些,以及更多Rails的魔力:)

代码语言:javascript
复制
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在奇异化的模型名称中工作得更好,如果不这样做,您可能会遇到一些问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17298471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档