has_oneとhas_manyの違いは多重度だけという思い込み
5367 ワード
のせいで、
親モデルと同時に子モデルをsave
する時
子モデルがinvalid
だったら、親モデルも保存しない。
これがhas_one
では素直にできませんでした。
class Parent < ActiveRecord::Base
has_one :first_child
validates :name, presence: true
end
class FirstChild < ActiveRecord::Base
validates :name, presence: true
end
parent = Parent.new(name: 'Oya')
parent.first_child = FirstChild.new
parent.save
# => true
parent.valid? # => true
parent.persisted? # => true
parent.first_child.valid? # => false
parent.first_child.persisted? # => false
has_many
と同じ挙動を期待していますが、
FirstChild
がinvalid
なのに、Parent
が保存されてしまいます。
Parent
が保存されないようにするには、このようにします。
class Parent < ActiveRecord::Base
has_one :first_child, validate: true
validates :name, presence: true
end
class FirstChild < ActiveRecord::Base
validates :name, presence: true
end
parent = Parent.new(name: 'Oya')
parent.first_child = FirstChild.new
parent.save
# => false
parent.valid? # => false
parent.persisted? # => false
parent.first_child.valid? # => false
parent.first_child.persisted? # => false
has_one
を宣言する時に、validate
オプションをtrue
にすると
期待通りになります。
ちなみにhas_many
は、このオプションはデフォルトでtrue
です。
参考
Author And Source
この問題について(has_oneとhas_manyの違いは多重度だけという思い込み), 我々は、より多くの情報をここで見つけました https://qiita.com/haazime/items/4d528f8d173d654ba394著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .