使用自定义名称在Rails中引用?

时间:2013-07-25 20:09:24

标签: ruby-on-rails ruby model

所以我正在开发一个rails应用程序,它将有两种用户,学生/导师。但我只有一个用户模型(使用cancan for auth),所以当我尝试设置会议模型(有一个导师和一个学生)时,我该怎么做?这是模型:

class Meeting < ActiveRecord::Base
  belongs_to :student
  belongs_to :tutor
  attr_accessible :price, :subject, :time
end

以下是架构的相关部分:

  create_table "meetings", :force => true do |t|
    t.string   "subject"
    t.integer  "student_id"
    t.integer  "tutor_id"
    t.datetime "time"
    t.integer  "price"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "meetings", ["student_id"], :name => "index_meetings_on_student_id"
  add_index "meetings", ["tutor_id"], :name => "index_meetings_on_tutor_id"

我不需要有两个包含学生和导师的额外模型,我可以使用这些标签吗?

2 个答案:

答案 0 :(得分:1)

一种方法......

class Meeting < ActiveRecord::Base
  belongs to :student, class_name: 'User'
  belongs to :tutor, class_name: 'User'

class User < ActiveRecord::Base
  has_many :meet_with_students, class_name: 'Meeting', foreign_key: :tutor_id
  has_many :students, through: :meet_with_students, source: :student
  has_many :meet_with_tutors, class_name: 'Meeting', foreign_key: :student_id
  has_many :tutors, through: :meet_with_tutors:, source: :tutor

答案 1 :(得分:0)

我认为你正在寻找class_name

class Meeting < ActiveRecord::Base
  belongs_to :student, class_name: "User"
  belongs_to :tutor, class_name: "User"
end