【问题标题】:Validate that an object has one or more associated objects验证一个对象是否有一个或多个关联对象
【发布时间】:2012-03-21 01:22:49
【问题描述】:

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

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

【问题讨论】:

标签: ruby-on-rails validation has-many-through


【解决方案1】:

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

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

  validates :categories, :length => { :minimum => 1 }
end

【讨论】:

  • 如何编写规范来测试这个?
  • @abhishek77in 我发现了一些说要使用it {should validate_length_of(:categories).is_at_least(1)} 的东西,但是我收到一个错误,说每个字符串的未定义方法。我认为测试存在性可能会起到作用,因为它需要至少有一个记录。
【解决方案2】:

我建议使用钩子方法而不是 wpgreenway 的解决方案,如 before_save 并使用 has_and_belongs_to_many 关联。

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

在您看来,使用可以使用例如options_from_collection_for_select

【讨论】:

    【解决方案3】:

    确保它至少有一个类别:

    class Product < ActiveRecord::Base
      has_many :product_categories
      has_many :categories, :through => :product_categories
    
      validates :categories, :presence => true
    end
    

    我发现使用:presence 的错误消息比使用length minimum 1 验证更清晰

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多