Ruby on rails 3.1 轨道3。决定是否保存对象

Ruby on rails 3.1 轨道3。决定是否保存对象,ruby-on-rails-3.1,save,Ruby On Rails 3.1,Save,我只是问自己,什么是解决我问题的最好办法 以下是我的模型: class Product < ActiveRecord::Base has_many :prices, :class_name => "ProductPrice" accepts_nested_attributes_for :prices end class ProductPrice < ActiveRecord::Base belongs_to :product end 我想做的是,当product

我只是问自己,什么是解决我问题的最好办法

以下是我的模型:

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

class ProductPrice < ActiveRecord::Base
  belongs_to :product
end
我想做的是,当product_price.value==nil或product_price.value==0.0时,防止保存所有ProductPrices

在产品价格中保存钩子之前。return false将回滚整个事务,这不是我想要做的。我只想用value==0或value==nil来调整所有价格 首先从params[…]中删除所有价格参数,然后调用Product。newparams[:Product]似乎不是rails的方式。。。 在Product.newparams[:Product]之后迭代所有价格并从数组中删除它们。但逻辑应该在我的模型中,对吗?我只是不想在每一个创造新价格的控制器上重复我自己。。。 有人能告诉我最好的解决办法吗?铁路是怎么走的


谢谢

你想要的是一个验证钩子,类似这样的东西:

class ProductPrice < ActiveRecord::Base
  belongs_to :product

  validates :value, :numericality => {:greater_than => 0.0 }
end
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])
请参阅,了解您可能希望通过更精细的控制来实现这一点的其他方法

为了避免首先添加这些无效价格,您可以从嵌套属性散列中删除它们,如下所示:

class ProductPrice < ActiveRecord::Base
  belongs_to :product

  validates :value, :numericality => {:greater_than => 0.0 }
end
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])

但这将回滚事务并在视图中引发一些错误。那不是我想要的。如果我执行product.save,那么我希望保存该产品,并且所有价格也>0!没有错误和回滚。如果是这样,您可以在传递到保存之前从嵌套属性散列中删除这些产品价格-请参阅更新。哦,这是个好主意。此解决方案的问题是,它不会覆盖其他控制器中的某些情况:price.value=0;价格。节省。这将破坏该对象。这是否可能?这是否可能发生在已经保存在数据库中的项目上,意味着记录应该被销毁?或者这仅仅是新记录的问题?是的,已经保存的对象应该被销毁,并且在这种情况下不应该保存新对象。