mor*_*utt 10 validation activerecord ruby-on-rails associations
如何才能使提交产品至少需要两个选项记录?
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
Run Code Online (Sandbox Code Playgroud)
kar*_*kie 17
class Product < ActiveRecord::Base
#... all your other stuff
validate :require_two_options
private
def require_two_options
errors.add(:base, "You must provide at least two options") if options.size < 2
end
end
Run Code Online (Sandbox Code Playgroud)
小智 12
只是考虑karmajunkie回答:我会使用size
而不是count
因为如果一些构建(而不是保存)的嵌套对象有错误,它将不会被考虑(它不在数据库上).
class Product < ActiveRecord::Base
#... all your other stuff
validate :require_two_options
private
def require_two_options
errors.add(:base, "You must provide at least two options") if options.size < 2
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4462 次 |
最近记录: |