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

时间:2015-09-26 22:26:26

标签: ruby-on-rails

我有一些问题概念化我的模型:用户与其他用户有1:N个任命。所以我创建了一个表Appointements和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

角色的用户一起参加课程

1 个答案:

答案 0 :(得分:1)

你有正确的想法,但你需要为列命名不同的东西。可能是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

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

只要您的约会涉及两个人,此设置才有效。如果可以有两个以上,或者如果你的课程应该有一个导师和任意数量的学生,你需要以不同的方式进行设置。制作Mentor的{​​{1}}和Student子类可能也是有益的,这样您就可以更好地区分它们。这是一个可能的骨架:

User