Rails的嵌套属性:至少需要两个记录 [英] Rails nested attributes: require at least two records

查看:117
本文介绍了Rails的嵌套属性:至少需要两个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让这个被要求至少有两个选项,记录提交产品?

 类产品<的ActiveRecord :: Base的
  belongs_to的:用户
  的has_many:选项:依赖=> :破坏
  accepts_nested_attributes_for:选项:allow_destroy => :真正的,:reject_if => PROC {| ATTRS | attrs.all? {| K,V | v.blank? }}
  validates_ presence_of:USER_ID,:created_at
  验证:描述:presence =>如此,:长度=> {:最小=> 0:最大=> 500}
结束

一流的选项<的ActiveRecord :: Base的
  belongs_to的:产品
  验证:姓名,:长度=> {:最小=> 0:最大=> 60}
结束
 

解决方案

 类产品<的ActiveRecord :: Base的
  #......所有其他的东西
  验证:require_two_options

  私人
    高清require_two_options
      errors.add(:基地,你必须至少提供两个选项),如果options.size< 2
    结束
结束
 

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

解决方案

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

这篇关于Rails的嵌套属性:至少需要两个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆