如何在validates_或validate_模型方法之外使用errors.add_to_base?

时间:2009-09-02 21:34:03

标签: ruby-on-rails

我有一个课程类有很多WeightingScales,我试图让WeightingScales验证通过系统传播。缺点是以下代码有效,除了errors.add_to_base()调用没有做任何事情(我可以​​看到)。 Course对象保存得很好,且WeightingScale对象无法保存,但我从未在控制器中看到错误。

  def weight_attributes=(weight_attributes)
    weighting_scales.each do |scale|
      scale.weight = weight_attributes.fetch(scale.id.to_s).fetch("weight")

      unless scale.save
        errors.add_to_base("The file is not in CSV format")
      end
    end
  end

我的问题与此1类似:如何在不使用“验证”方法的情况下向模型添加错误?

link text

2 个答案:

答案 0 :(得分:1)

如果您希望保存失败,则需要使用validate方法。如果没有,你将不得不使用像before_save或before_create这样的回调来检查errors.invalid吗?在允许保存通过之前是错误的。就个人而言,我只会使用验证。希望它有帮助=)

答案 1 :(得分:0)

我遇到了类似的问题,我想验证一个永远不需要保存到模型中的参数(只是一个确认标志)。

如果我这样做了:

@user.errors.add_to_base('You need to confirm') unless params[:confirmed]
if @user.save
  # yay
else
  # show errors
end

它不起作用。我没有深入研究来源,但是在控制台中玩游戏看起来好像在运行验证之前调用@user.save@user.valid?清除了@user.errors

我的解决方法是做类似的事情:

if @user.valid? && params[:confirmed]
  @user.save
  # redirect to... yay!
elsif !params[:confirmed]
  @user.errors.add_to_base('You need to confirm')
end
# show errors

运行验证后添加到基础的错误会在视图中正确显示。

但这与您的情况略有不同,因为您似乎想要在setter中添加错误而不是控制器操作。您可能希望查看before_validation或after_validation。