has_many の要素を update_attributes する際に uniqueness validation が効かない
class Man < ActiveRecord::Base
has_many :cards
accepts_nested_attributes_for :cards
end
class Card < ActiveRecord::Base
belongs_to :man
validates :number, uniqueness:{ scope: :suite }
end
m = Man.new
m.update_attributes({
cards_attributes: [
{ suite: "spade", number: "4" }, #(1)
{ suite: "spade", number: "4" }, #(2)
{ suite: "club", number: "6" }, #(3)
]
})
Card の validation が走る時点で、 #(1) はDB上に存在しないので、#(2) の validation がまんまと通ってしまう。
update_attributes を使わずに、
m.cards << Card.new(suite: "spade", number: "4")
などと1つずつ入れればもちろんOKなのだが。。