Validate that an object has one or more associated objects

核能气质少年 提交于 2019-11-28 22:53:17

问题


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

回答1:


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



回答2:


Ensures it has at least one category:

class Product < ActiveRecord::Base
  has_many :product_categories
  has_many :categories, :through => :product_categories

  validates :categories, :presence => true
end

I find the error message using :presence is clearer than using length minimum 1 validation




回答3:


Instead of wpgreenway's solution, I would suggest to use a hook method as before_save and use a has_and_belongs_to_many association.

class Product < ActiveRecord::Base
  has_and_belongs_to_many :categories
  before_save :ensure_that_a_product_belongs_to_one_category

  def ensure_that_a_product_belongs_to_one_category
    if self.category_ids < 1 
      errors.add(:base, "A product must belongs to one category at least")
      return false
    else
      return true
    end
  end   

class ProductsController < ApplicationController
  def create
    params[:category] ||= []
    @product.category_ids = params[:category]
    .....
  end
end

And in your view, use can use for example options_from_collection_for_select



来源:https://stackoverflow.com/questions/9535012/validate-that-an-object-has-one-or-more-associated-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!