Validate that an object has one or more associated objects

我只是一个虾纸丫 提交于 2019-11-30 02:47:45
wpgreenway

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
Adrian

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

ftanguy

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

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