【问题标题】:How to handle master-detail with STI如何使用 STI 处理主从细节
【发布时间】:2012-03-24 09:16:14
【问题描述】:

如果角色是 STI 表:

class Role< ActiveRecord::Base
   self.inheritance_column= :role_type 
end

学生和辅导员继承角色:

class Student< Role
end

class Counselor< Role
end

StudentDetail 保留有关一名学生的额外信息:

class StudentDetail< ActiveRecord::Base
    belongs_to :student
end

用户既可以是学生也可以是辅导员:

class User< ActiveRecord::Base
    has_many :roles
    has_one :student
    has_one :counselor
end

而数字是StudentDetail中的一列, 而role_id是StudentDetail中的一列

是否有可能使以下语法起作用?

User.first.student.number

含义:“如果 Role 表有一个学生 user_id == User.first.id 那么 User.first.student 不为 null 并且如果 StudentDetail 有 role_id== Student.where("user_id= ?", User.first .id).first.id,让“student”作为StudentDetail记录,获取number字段。”

【问题讨论】:

    标签: ruby-on-rails activerecord polymorphic-associations single-table-inheritance


    【解决方案1】:

    您将拥有开箱即用的间接User.first.student.student_detail.number。我不认为这很痛:-)

    我看到两个选项(至少)如何走得更远:

    • Student中的StudentDetail方法定义方法:

      def number
        self.student_detail ? self.student_detail.number : nil
      end
      
    • 使用缺少的方法自动执行此操作:

      def method_missing(name, *args, &block)
        self.student_detail ? self.student_detail.send(name, *args, &block) : nil
      end
      

    【讨论】:

    • 井定义号; self.try(:student_detail).try(:number); end 会更简洁。我最终做了“has_one student_detail through student”,但为 method_missing +1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多