加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails accepted_nested_attributes计数验证

发布时间:2020-12-17 02:54:11 所属栏目:百科 来源:网络整理
导读:我有三个型号.销售,物品和图像.我想验证,在创建促销时,每次促销至少有三张照片和一件或多件商品.实现这一目标的最佳方法是什么? 销售模式: class Sale ActiveRecord::Base has_many :items,:dependent = :destroy has_many :images,:through = :items acce
我有三个型号.销售,物品和图像.我想验证,在创建促销时,每次促销至少有三张照片和一件或多件商品.实现这一目标的最佳方法是什么?

销售模式:

class Sale < ActiveRecord::Base
   has_many :items,:dependent => :destroy
   has_many :images,:through => :items

   accepts_nested_attributes_for :items,:reject_if => lambda { |a| a[:title].blank? },:allow_destroy => true
end

物品型号:

class Item < ActiveRecord::Base

  belongs_to :sale,:dependent => :destroy
  has_many :images,:dependent => :destroy

  accepts_nested_attributes_for :images

end

图像型号:

class Image < ActiveRecord::Base
  belongs_to :item,:dependent => :destroy
end

解决方法

创建用于验证的自定义方法

在您的销售模型中添加如下内容:

validate :validate_item_count,:validate_image_count

def validate_item_count
  if self.items.size < 1
    errors.add(:items,"Need 1 or more items")
  end
end

def validate_image_count
  if self.items.images.size < 3
    errors.add(:images,"Need at least 3 images")
  end
end

希望这会有所帮助,祝你好运和编码愉快.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读