我只想做一个连接表,最终在该连接上存储额外的信息(这就是为什么我不使用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 end create_table "physicians",:null => false end end
当我在控制台中,我创建了一名医师和病人的实例:
@patient = Patient.create! @physician = Physician.create!
并试图将一个与另一个相关联
@physician.patients << @patient
我得到
NameError: uninitialized constant Physician::Patients
有关此示例的问题之前已经提出过,但没有一个解决我的情况.有任何想法吗?
谢谢,
Neil,rails newbie.
解决方法
在你的预约模型中的belongs_to调用应该采用单数形式,而不是复数形式:
class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end