У меня есть модель Order
, в которой может быть много texts
.
Текст может иметь вложение activestorage, и я проверяю это вложение с помощью active_storage_validations
gem.
IЯ хочу сохранить действительные тексты и отклонить недействительные тексты, поэтому я использую опцию reject_if
в accepts_nested_attributes_for
... но я хочу сохранить ошибки, а затем визуализировать форму, если текст был отклонен.
Это мой код:
class Order < ApplicationRecord
has_many :texts, dependent: :destroy, validate: false
accepts_nested_attributes_for :texts, allow_destroy: true, reject_if: :invalid_text?
def invalid_text?(attributes)
text = Text.new(attributes.tap { |att| att.delete(:_destroy) })
return if text.valid?
text.errors.full_messages.each do |msg|
errors.add(:base, msg)
end
end
end
Тогда в моем контроллере:
def update
if @order.update(order_params)
@order.update!(creation_step: 'instructions')
check_if_documents(@order, params[:file_upload_method])
Text.counter_culture_fix_counts
jump_to(:instructions)
else
flash.now.alert = @order.errors.full_messages.join('. ') if @order.errors.messages.any?
render(:show)
end
end
Проблема в том, что reject_if
вызывается после @order.update
, поэтому ошибок не бывает.
Как проверить вложенные атрибуты перед родительским обновлением, имея доступ к атрибутам activestorage?
Если я выполняю обратный вызов before_validation
, атрибуты ActiveStorage недоступны при методе nested_attributes_options
..