【问题标题】:Rails has many and belongs to between two times with same modelsRails 有很多,属于同型号的两次之间
【发布时间】:2014-01-23 21:57:06
【问题描述】:

我想知道该怎么做,如果有人知道我会很高兴听到。我有以下型号

User
Usertype
Course

我有两种类型的用户 - 学生和教师。 我想要的是两张桌子

CourseTeacher - course_id, teacher_id 
CourseStudent - course_id, student_id

我的用户模型有usertype_id 列。所以我想知道在这种情况下如何使用has_many_and_belongs_to,因为一切都取决于用户模型中的usertype_id 列。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-4 ruby-on-rails-3.1


    【解决方案1】:

    我认为类继承是一种更简洁的方式来为您的域逻辑建模:

    class User < ActiveRecord::Base
    end
    
    class Student < User
    end
    
    class Teacher < User
    end
    

    然后表格将有一个idtype 列,大大简化了您要完成的工作。阅读 API 文档以了解更多信息:Single Table Inheritance

    【讨论】:

      【解决方案2】:

      如果你没有重构的能力,你可以尝试使用这种方法:

      创建一个而不是 2 个表:

      class CoursesUsers
        belongs_to :course
        belongs_to :user
      end
      

      在用户模型中自己决定逻辑(对我来说似乎是多态的)

      【讨论】:

        猜你喜欢
        • 2011-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多