【问题标题】:Accessing validation context in a callback在回调中访问验证上下文
【发布时间】:2021-04-16 09:20:16
【问题描述】:

我正在重构一个旧的(和大量的)Rails 应用程序,我想知道是否可以在 validation callback 中访问 ActiveRecord context

目前的代码是这样的

class Operation < ApplicationRecord
  attr_accessor :requires_update

  after_validation :update_status
  ...

  def update_status
   case status
   when 1
     ...
   when 10
    if requires_update
      status = 11
    end
  end
  ...
end
class OperationsController < ApplicationController
  def mark_as_complete
    ...
    if @operation.update(operation_params)
     ...
    else
      ...
    end
  end
  ...
end
<%= form_for @operation, url: mark_as_complete_operation_path(@operation) do |form| %>
  <%= hidden_field :operation, :requires_update, value: "1" %>
  ...
<% end %>

我想做的是:

1- 删除表单中的hidden_field(这是表单发布到控制器的唯一值)。

2- 在特定上下文中保存operation

def mark_as_complete
    ...
    if @operation.save(context: :completed)
     ...
    else
      ...
    end
  end
  ...

3- 在update_status 方法中访问上下文。

def update_status
  ...
   when 10
    if CONTEXT == :completed # What should go here?
      status = 11
    end
  end

有没有办法做到这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
      if @operation.save(context: :completed)
    

    在保存之前在completed 上下文中验证operation。这意味着您可以在该上下文中调用验证。我没有找到任何文档说您可以在 after_validation 回调中以您希望使用的方式使用上下文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-02
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2012-01-02
      • 2017-06-15
      相关资源
      最近更新 更多