10

小さな結合テーブルを作成し、最終的にその結合に関する追加情報を格納したいだけです(これが、HABTMを使用していない理由です)。アソシエーションのレールドキュメントから、次のモデルを作成しました。

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

この例についての質問は以前に尋ねられましたが、私のシナリオに対処したものはありません。何か案は?

ありがとう、ニール、レール初心者。

4

1 に答える 1

18

モデル内のbelongs_to呼び出しはAppointment、複数形ではなく単数形にする必要があります。

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end
于 2013-01-15T22:24:52.180 に答える