Rails嵌套属性:至少需要两条记录

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)

  • options.count将生成SQL COUNT查询以查找您拥有的选项数.如果您的选项在内存中,而不是保存在数据库中,则会产生意外答案,因为它们不会包含在计数中.[在这种情况下考虑使用大小.](http://stackoverflow.com/questions/6083219/activerecord-size-vs-count) (4认同)

小智 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)