0

我只是问自己,我的问题的最佳解决方案是什么。

这是我的模型:

class Product < ActiveRecord::Base
  has_many :prices, :class_name => "ProductPrice"
  accepts_nested_attributes_for :prices
end

class ProductPrice < ActiveRecord::Base
  belongs_to :product
end

控制器

def create
  @product = Product.new(params[:product])

  @product.save
  ...
end

我想要做的是防止所有 ProductPrices 被保存时product_price.value == nilproduct_price.value == 0.0

  1. before_save挂钩 ProductPrice。return false 将回滚整个事务,这不是我想要做的。我只想“踢”所有价格value == 0 or value == nil
  2. 首先踢出所有 price_paramsparams[...]然后调用Product.new(params[:product])似乎不是轨道方式八...
  3. Product.new(params[:product])遍历所有价格并将它们从数组中删除之后。但逻辑应该在我的模型中,对吗?我只是不想在每一个创造新价格的控制器上重复自己……

有人可以告诉我最好的解决方案吗?什么是铁轨方式?

谢谢!

4

1 回答 1

0

What you want it called a validation hook, something like this:

class ProductPrice < ActiveRecord::Base
  belongs_to :product

  validates :value, :numericality => {:greater_than => 0.0 }
end

See http://guides.rubyonrails.org/active_record_validations_callbacks.html for other ways you may want to do this with finer control.

To avoid adding these invalid prices in the first place, you can remove them from the nested attributes hash like this:

class Product < ActiveRecord::Base
  def self.clean_attributes!(product_params)
    product_prices = product_params['prices'] || []
    product_prices.reject!{|price| price['value'].to_f == 0 rescue true }
  end
end

Product.clean_attributes!(params[:product])
Product.new(params[:product])
于 2012-07-09T20:03:54.723 回答