Last active
August 29, 2015 14:13
-
-
Save flada-auxv/052f5dfff9b8a8b2aec5 to your computer and use it in GitHub Desktop.
has_many :through な関連で accepts_nested_attributes_for を定義している時、親オブジェクトが保存されていない状態で子オブジェクトとの関連付けを行うと、外部キーが nil な中間テーブルの record を insert して死ぬ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association | |
##### Model ##### | |
class Physician < ActiveRecord::Base | |
has_many :appointments | |
has_many :patients, through: :appointments | |
accepts_nested_attributes_for :appointments | |
end | |
class Appointment < ActiveRecord::Base | |
belongs_to :physician | |
belongs_to :patient | |
end | |
class Patient < ActiveRecord::Base | |
has_many :appointments | |
has_many :physicians, through: :appointments | |
end | |
##### Migration ##### | |
create_table "appointments", force: true do |t| | |
t.integer "physician_id", null: false | |
t.integer "patient_id", null: false | |
t.datetime "appointment_date" | |
t.datetime "created_at" | |
t.datetime "updated_at" | |
end | |
add_index "appointments", ["patient_id"], name: "index_appointments_on_patient_id", using: :btree | |
add_index "appointments", ["physician_id"], name: "index_appointments_on_physician_id", using: :btree | |
create_table "patients", force: true do |t| | |
t.string "name" | |
t.datetime "created_at" | |
t.datetime "updated_at" | |
end | |
create_table "physicians", force: true do |t| | |
t.string "name" | |
t.datetime "created_at" | |
t.datetime "updated_at" | |
end | |
##### Example ##### | |
describe '' do | |
before do | |
Patient.create | |
end | |
it { | |
expect { | |
physician = Physician.new | |
physician.patients = [Patient.first] | |
physician.save! | |
}.to_not raise_error | |
# 4.1.1 => passed | |
# 4.1.2 => expected no Exception, got #<ActiveRecord::StatementInvalid: | |
# Mysql2::Error: Field 'physician_id' doesn't have a default value: | |
# INSERT INTO `appointments` (`created_at`, `patient_id`, `updated_at`) VALUES ('2015-01-23 04:01:18', 12, '2015-01-23 04:01:18')> | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment