我只想制作一个小连接表,最终在该连接上存储额外的信息(这就是我不使用HABTM的原因)。从关联的rails文档中我创建了以下模型:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physicians
belongs_to :patients
end
我的架构如下所示:
ActiveRecord::Schema.define(:version => 20130115211859) do
create_table "appointments", :force => true do |t|
t.datetime "date"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "patient_id"
t.integer "physician_id"
end
create_table "patients", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "physicians", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
当我在控制台中时,我创建了一个医生和患者实例:
@patient = Patient.create!
@physician = Physician.create!
尝试将一个与另一个相关联
@physician.patients << @patient
我得到了
NameError: uninitialized constant Physician::Patients
以前曾询问过有关此示例的问题,但没有一个解决我的问题。有什么想法吗?
谢谢, 尼尔,铁路新手。
答案 0 :(得分:17)
belongs_to
模型中的Appointment
来电应采用单数形式,而不是复数形式:
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end