验证一个对象具有一个或多个关联对象

编程入门 行业动态 更新时间:2024-10-26 04:22:25
本文介绍了验证一个对象具有一个或多个关联对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要确保在创建产品时,它至少具有一个类别. 我可以使用自定义验证类来做到这一点,但我希望有一种更标准的方法来实现它.

I need to ensure that when a product is created it has atleast one category. I could do this with a custom validation class, but I was hoping there was a more standard way of doing it.

class Product < ActiveRecord::Base has_many :product_categories has_many :categories, :through => :product_categories #must have at least 1 end class Category < ActiveRecord::Base has_many :product_categories has_many :products, :through => :product_categories end class ProductCategory < ActiveRecord::Base belongs_to :product belongs_to :category end

推荐答案

有一个验证将检查您的关联的长度.试试这个:

There is a validation that will check the length of your association. Try this:

class Product < ActiveRecord::Base has_many :product_categories has_many :categories, :through => :product_categories validates :categories, :length => { :minimum => 1 } end

更多推荐

验证一个对象具有一个或多个关联对象

本文发布于:2023-11-22 08:30:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616695.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   多个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!