I'm refactoring an old (and massy) Rails app and I'm wondering if it's possible to access an ActiveRecord context in a validation callback.
The current code looks like
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 %>
What I'd like to do is:
1- Removing the hidden_fieldin the form (which is the only value the form posts to the controller).
2- Saving the operation within a specific context.
def mark_as_complete
...
if @operation.save(context: :completed)
...
else
...
end
end
...
3- Accessing the context in the update_status method.
def update_status
...
when 10
if CONTEXT == :completed # What should go here?
status = 11
end
end
Is there a way to achieve that?
if @operation.save(context: :completed)
validates operation in the completed context before saving it. That means that you can call a validation on that context. I don't find any docs saying you can use context in the way you want to use it in an after_validation callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With