【问题标题】:Rails, model relationship child-parentRails,模型关系子父
【发布时间】:2018-01-28 00:17:25
【问题描述】:

我有一个简单的应用程序,我必须将学生与家长之间的关系描述为多对多,其中以下方法可行:

current_user.parents

current_user.children

目前我有以下

class User < ApplicationRecord
  has_many :parent_students
  has_many :students, through: :parent_students, class_name: "User"
  has_many :parents,  through: :parent_students, class_name: "User"
end

class ParentStudent < ApplicationRecord
    belongs_to :student, class_name: "User", foreign_key: "student_id"
    belongs_to :parent,  class_name: "User", foreign_key: "parent_id"
end

class CreateParentStudents < ActiveRecord::Migration[5.1]
  def change
    create_table :parent_students do |t|
        t.references :student, index: true, references: :users
        t.references :parent,  index: true, references: :users

      t.timestamps
    end
  end
end

知道这将如何工作吗?谢谢!

【问题讨论】:

    标签: ruby-on-rails database-design


    【解决方案1】:

    可能这会有所帮助,用户内部的声明

    class User < ActiveRecord::Base
      # as parent
        has_many: student_relations, foreign_key: :parent_id, class_name: "ParentStudent"
        has_many: students, through: :student_relations, source: :student
      # as student
        has_many: parent_relations, foreign_key: :student_id, class_name: "ParentStudent"
        has_many: parents, through: :parent_relations, source: :parent
    end
    
    class ParentStudent < ActiveRecord::Base
      belongs_to :student, foreign_key: "student_id", class_name: "User"
      belongs_to :parent,  foreign_key: "parent_id",  class_name: "User"
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2015-03-05
      • 2015-10-13
      • 2021-04-25
      相关资源
      最近更新 更多