简体   繁体   English

验证:在 Rails Controller 中使用自定义方法

[英]Validate :on with custom method in Rails Controller

I want to do a put/patch to the following route which in return calls the bars controller and calls its update_premium method: put '/bar/premium', to: 'bars#update_premium'我想对以下路线做一个放置/补丁,作为回报,它会调用酒吧 controller 并调用它的 update_premium 方法: put '/bar/premium', to: 'bars#update_premium'

However that method should call a validation check in the model itself whenever.save or.valid?/.valid is called.但是,每当调用 .save 或 .valid?/.valid 时,该方法都应在 model 本身中调用验证检查。

bar.rb

class Bar < ApplicationRecord
    belongs_to :city
    validate :validate_premium_bars, on: :create
    validate :validate_premium_bars, on: :update_premium

    def allow
        @allow_change = true
    end

    private
    def validate_premium_bars
        return unless self.city
        unless @allow_change
            if self.city.bars.where(:is_premium => true).count >= 5
                errors.add("...")
            end
        end
    end
end

bars_controller.rb

def update_premium
        @bar = Bar.find(params[:id])
        if @bar.save
            ...
        else
            render json: @bar.errors.full_messages, status: 400
        end
end

It works when I use on: :update however a custom method in the controller such as on: :update_premium doesn't work together with the "on:" symbol.它在我使用on: :update时有效,但是 controller 中的自定义方法,例如on: :update_premium不能与“on:”符号一起使用。

How can I resolve this?我该如何解决这个问题? I want to keep the update method in the controller for a real full model update and not just for triggering one attribute of the model.我想将更新方法保留在 controller 中,以进行真正的完整 model 更新,而不仅仅是触发 model 的一个属性。

Considering the situation in this question I would actually suggest just adding validation as:考虑到这个问题的情况,我实际上建议将验证添加为:

validate :validate_premium_bars

So it runs every time you run valid?所以每次运行valid? or save is called instead of adding specific conditions for create and update .save被调用,而不是为createupdate添加特定条件。

In case, you want to add this separately for some reason.如果您出于某种原因想要单独添加它。 You can add the validation to run for update and update the actual attribute using the update call or call valid?您可以添加验证以运行update并使用update调用或调用valid? on it after value check to make sure that the record passes validations在值检查后对其进行检查以确保记录通过验证

The problem is that the update controller action is no mapped to the model actions.问题是update controller 操作没有映射到 model 操作。 One refers to an endpoint and the other refers to an event in the model lifecycle.一个指端点,另一个指 model 生命周期中的事件。 Looks at the official documentation about validation options.查看有关验证选项的官方文档

You can create a custom conditional validation to run each time the model is changed.您可以创建自定义条件验证以在每次更改 model 时运行。 For example:例如:

  validate :validate_premium_bars, if: :allowed_chage?
 
  def allowed_chage?
    @allowed_chage
  end

soruce 来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM