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

时间:2010-11-30 00:05:34

标签: ruby-on-rails validation activerecord 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

4 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分: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

答案 2 :(得分:2)

如果您的表单允许删除记录,则.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

答案 3 :(得分:0)

Tidier代码,使用Rails 5测试:

    public ActionResult PeriodSelection(string dropdownlistReturnValue) // dont know what dropdownlistReturnValue is doing?
    {
        Session["Period"] = dropdownlistReturnValue;
        return PartialView("~/Views/Employee/_PnlChart.cshtml");
    }