Rails 3:嵌套 fields_for 的唯一性验证
A 有两个模型,“shop”和“product”,通过 has_many :through 链接。
在商店表单中,有多个产品的嵌套属性,并且我在产品的唯一性验证方面遇到了一些麻烦。如果我输入一个产品,保存它,然后尝试为新产品输入相同的名称,则唯一性验证会成功触发。
但是,如果我在同一嵌套表单的两行中输入相同的产品名称,则该表单将被接受 - 不会触发唯一性验证。
我猜这是一个相当常见的问题,但我找不到任何简单的解决方案。有人对确保在相同嵌套表单中遵守唯一性验证的最简单方法有任何建议吗?
编辑:产品型号如下
class Product < ActiveRecord::Base
has_many :shop_products
has_many :shops, :through => :shop_products
validates_presence_of :name
validates_uniqueness_of :name
end
A have two models, "shop" and "product", linked via has_many :through.
In the shop form there are nested attributes for multiple products, and I'm having a little trouble with the product's uniqueness validation. If I enter a product, save it, then try to enter the same name for a new product, the uniqueness validation triggers successfully.
However, if I enter the same product name in 2 rows of the same nested form, the form is accepted - the uniqueness validation doesn't trigger.
I'm guessing this is a fairly common problem, but I can't find any simple solution. Anyone have any suggestions on the easiest way to ensure uniqueness validations are obeyed within the same nested form?
Edit: Product model included below
class Product < ActiveRecord::Base
has_many :shop_products
has_many :shops, :through => :shop_products
validates_presence_of :name
validates_uniqueness_of :name
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
早期的答案确实很好,虽然它们是一个很好的起点,但已经过去了几年了!
这是一个最新的选项!
success_response 和 failure_response 可以是您需要的任何内容!
The earlier answers are really good, and while they were a great starting point, it has been a few years!
Here's an up-to-date option!
With success_response and failure_response being whatever you need them to be!
为了扩展 Alberto 的解决方案,以下自定义验证器接受要验证的字段(属性),并向嵌套资源添加错误。
To expand on Alberto's solution, the following custom validator accepts a field (attribute) to validate, and adds errors to the nested resources.
您可以编写一个自定义验证器,例如
You could write a custom validator like
我在这里找到了答案:
https://rails.lighthouseapp。 com/projects/8994/tickets/2160-nested_attributes-validates_uniqueness_of-fails
I found the answer over here :
https://rails.lighthouseapp.com/projects/8994/tickets/2160-nested_attributes-validates_uniqueness_of-fails