ruby-on-rails Rails嵌套属性:至少需要两条记录

xpcnnkqh  于 2023-03-24  发布在  Ruby
关注(0)|答案(5)|浏览(136)

我怎样才能使它至少需要两个选项记录提交产品?

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
uinbv5nw

uinbv5nw1#

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
q1qsirdb

q1qsirdb2#

只是一个关于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
vd8tlhqk

vd8tlhqk3#

如果您的表单允许删除记录,则.size将无法工作,因为它包含标记为销毁的记录。
我的解决方案是:

validate :require_two_options

private
 def require_two_options
    i = 0
    product_options.each do |option|
      i += 1 unless option.marked_for_destruction?
    end
    errors.add(:base, "You must provide at least two option") if i < 2
 end
vwoqyblh

vwoqyblh4#

更整洁的代码,使用Rails 5测试:

class Product < ActiveRecord::Base
  OPTIONS_SIZE_MIN = 2
  validate :require_two_options

  private

  def options_count_valid?
    options.reject(&:marked_for_destruction?).size >= OPTIONS_SIZE_MIN
  end

  def require_two_options
    errors.add(:base, 'You must provide at least two options') unless options_count_valid?
  end
end
jucafojl

jucafojl5#

我想知道为什么没有人提到这个简单的解决方案。只需将此添加到您的父类:

class Product < ActiveRecord::Base

  ...
  
  validates :options, :length => { :minimum => 2 }

end

在Rails 5.2.8(可能还有更高版本)中工作对我来说很有魅力。

相关问题