VOOZH about

URL: https://qiita.com/haazime/items/4d528f8d173d654ba394

⇱ has_oneとhas_manyの違いは多重度だけという思い込み #Rails - Qiita


👁 Image
21

Go to list of users who liked

14

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 5 years have passed since last update.

@haazime

has_oneとhas_manyの違いは多重度だけという思い込み

21
Last updated at Posted at 2015-03-04

のせいで、
親モデルと同時に子モデルを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と同じ挙動を期待していますが、
FirstChildinvalidなのに、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です。

参考

21

Go to list of users who liked

14
0

Go to list of comments

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21

Go to list of users who liked

14