Rails 嵌套属性:需要至少两条记录
如何才能使提交产品时至少需要两条选项记录?
class Product < ActiveRecord::Base
belongs_to :user
has_many :options, :dependent => :destroy
accepts_nested_attributes_for :options, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
validates_presence_of :user_id, :created_at
validates :description, :presence => true, :length => {:minimum => 0, :maximum => 500}
end
class Option < ActiveRecord::Base
belongs_to :product
validates :name, :length => {:minimum => 0, :maximum => 60}
end
How can I make it so that at least two option records are required to submit a product?
class Product < ActiveRecord::Base
belongs_to :user
has_many :options, :dependent => :destroy
accepts_nested_attributes_for :options, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
validates_presence_of :user_id, :created_at
validates :description, :presence => true, :length => {:minimum => 0, :maximum => 500}
end
class Option < ActiveRecord::Base
belongs_to :product
validates :name, :length => {:minimum => 0, :maximum => 60}
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只是考虑一下 karmajunkie 答案:我会使用
size
而不是count
因为如果某些构建(且未保存)的嵌套对象有错误,则不会考虑它(它不是尚未在数据库上)。Just a consideration about karmajunkie answer: I would use
size
instead ofcount
because if some built (and not saved) nested object has errors, it would not be considered (its not on database yet).如果您的表单允许删除记录,则
.size
将不起作用,因为它包含标记为销毁的记录。我的解决方案是:
If your form allows records to be deleted then
.size
will not work as it includes the records marked for destruction.My solution was:
更整洁的代码,用 Rails 5 测试:
Tidier code, tested with Rails 5:
我想知道为什么没有人提到这个简单的解决方案。只需将其添加到您的父类中:
在 Rails 5.2.8(也可能更高版本)中对我来说就像一个魅力。
I wonder why nobody mentioned this simple solution. Just add this to your parent class:
Works like a charm to me in Rails 5.2.8 (and probably above as well).