Rails:如何为与其他用户有许多约会的用户建模



我在概念化我的模型时遇到了一些问题:一个用户与另一个用户有1:N个约会。所以我创建了一个表appointments和Users,但是对于连接表,我最终在索引中有2个user_id,这是错误的。

class AppointmentsUsersJointTable < ActiveRecord::Migration
  def change
    create_table :appointments_users, id: false do |t|
      t.integer :user_id
      t.integer :user_id
      t.integer :appointment_id
    end
    add_index :appointments_users, :user_id
    add_index :appointments_users, :user_id
    add_index :appointments_users, :appointment_id
  end
end
#app/model/user.rb
has_and_belongs_to_many :users

其他详细信息:一个用户最多可以有两个角色(Rolify),它是:students:mentor。因此,具有角色(学生)的用户希望与具有角色:mentor的用户一起学习课程

您的想法是正确的,但是您需要为列命名不同的名称。可能是student_idmentor_id

class AppointmentsUsersJoinTable < ActiveRecord::Migration
  def change
    create_table :appointments_users, id: false do |t|
      t.integer :student_id
      t.integer :mentor_id
      t.integer :appointment_id
    end
    add_index :appointments_users, :student_id
    add_index :appointments_users, :mentor_id
    add_index :appointments_users, :appointment_id
  end
end

当您在User类中声明关联时,您需要使用foreign_key选项指定这些自定义列名。

只有当你的约会涉及两个人时,这个设置才会起作用。如果可以有两个以上的导师,或者你的课程应该有一个导师和任意数量的学生,你需要不同的设置。将MentorStudent作为User的子类也可能是有益的,这样可以更好地区分它们。这里有一个可能的骨架:

class User; end
class Mentor < User
  has_many :courses
  has_many :students, through: :courses
end
class Student < User
  has_many :enrollments
  has_many :courses, through: :enrollments
  has_many :mentors, through: :courses
end
class Course
  belongs_to :mentor
  has_many :enrollments
  has_many :students, through: :enrollments
end
class Enrollment
  belongs_to :course
  belongs_to :student
end

相关内容

最新更新