如何在 before_save 关联回调中添加验证错误 [英] How can I add a validation error in before_save association callbacks

查看:32
本文介绍了如何在 before_save 关联回调中添加验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种模式:Discount 拥有并属于许多企业.

I have two models: The Discount has and belongs to many Businsses.

我想验证一个折扣总是至少有一个业务,以及另一个条件(例如 active?).我尝试了以下方法:

I want to validate that a Discount always have at least one business, together with another condition (for example active?). I tried the following:

class Discount < ActiveRecord::Base
  has_and_belongs_to_many :businesses,
    before_remove: :validate_publish_status

  def validate_publish_status(*arg)
    if active? && businesses.count == 0
      errors[:active] << 'discount with no business'
    end
  end
end

但是这不起作用(没有引发验证错误),我意识到这可能是因为它只是一个回调,而不是验证.我该如何编码,以便我可以像使用自定义验证一样使用 errors?

However this does not work (no validation errors raised) and I realized that this is probably because it is only a callback, not a validation. How can I code it so I can use the errors like I do I custom validation?

我拥有的控制器操作(用于 ajax):

The controller action I have (for ajax):

  def remove
    @business = Business.find(params[:business_id])
    if @business.in? @discount.businesses
      @discount.businesses.delete(@business)
    end
    render json: @business.as_json(only: [:id, :type, :name, :address],
                                   methods: [:city_name, :country_name]).
      merge(paths: paths_for(@discount, @business))
  rescue ActiveRecord::RecordInvalid # even tried the generic Exception
    respond_to do |f|
      f.json { render json: {error: $!.message}, status: 403 }
    end
  end

推荐答案

可能是您在 before_remove 回调中的语法或验证方法本身发生的事情.您可能还想在回调方法中添加一些调试代码,以查看它是否在其中生成.

Could be your syntax on the before_remove callback or what's happening in the validation method itself. You also might want to add some debug code in the callback method to see if it's even making in there.

*注意只有在回调方法中引发异常时才会停止事务.由于是这种情况,您可能希望处理控制器中的异常逻辑以重新呈现操作:

*Note that the transaction will only be stopped if an exception is raised in the callback method. Since this is the case, you'll probably want to handle the exception logic in your controller to re-render the action:

class Discount < ActiveRecord::Base
  has_and_belongs_to_many :businesses, :before_remove => :validate_publish_status

  def validate_publish_status(*args)
   if yyy? && businesses.count == 0
    errors.add(:yyy,'discount with no business')
    raise "Unable to remove business."
   end
  end

end

控制器要点:

  def update
    @company.find(params[:id])
    if @company.update_attributes(params[:company])
      ...
    else
      render :action => 'edit'
    end
  rescue
    render :action=>'edit'
  end

请注意关联回调文档.

这篇关于如何在 before_save 关联回调中添加验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆