【发布时间】:2013-11-20 15:59:41
【问题描述】:
我需要验证一个包含相关集合的模型,该集合需要
在 has_many 集合中唯一的字段。
例如,如果我有以下课程:
class Match < ActiveRecord::Base
has_many :match_items, dependent: :destroy
validates_associated :match_items
end
class MatchItem < ActiveRecord::Base
belongs_to :match
validates_uniqueness_of :user_type, scope: :match_id
end
我创建一个这样的匹配:
items = [
MatchItem.new(user_type: 'test'),
MatchItem.new(user_type: 'test')
]
match = Match.new(match_items: items)
match.save # Erroneously returns true
我希望匹配创建失败。
虽然 MatchItem 类中的唯一性验证器确实 阻止集合包含多个用户类型,但我更希望匹配创建失败。相反,虽然它只包含指定的匹配项之一,但匹配创建时没有错误。
我认为问题在于validates_associated 在保存 Match 之前在每个 MatchItem 上调用 valid?,但每个 MatchItem 在添加到 Match 之前 自身有效。
当 match_items 集合不包含唯一值时,防止 Match 保存的最佳方法是什么?
【问题讨论】:
-
你为什么不能把所有东西都包装在一个 AR.transaction 块中并使用
create!? -
@PhilipHallstrom 我无法使用
create!调用将其包装在事务中的原因是它不会引发错误,尽管事实上只有一个关联的匹配项是已保存。
标签: ruby-on-rails activerecord ruby-on-rails-4 associations