I have 2 models
class A < ApplicationRecord
has_one :b, dependent: :destroy
has_one :c, dependent: :destroy
end
and
class B < ApplicationRecord
belongs_to :a
validates :ip_address, presence_true, format : {with: regex,message:"must be valid"}
end
While saving / updating above records,
transaction do
save_b(params)
save_c(params)
rescue ActiveRecord::RecordNotSaved => e
handle_error
rescue ActiveRecord::RecordInvalid => e
handle_error
end
save_b(params)
self.b ||= build_b(params)
b.update!(params)
end
If invalid ip_address
is sent in params, above code rescues in ActiveRecord::RecordNotSaved
block. How can I refactor so that error rescues in ActiveRecord::RecordInvalid
and I get error message defined for ip_address
in model B
2
ActiveRecord::RecordInvalid
will be triggered if you use save!
or create!
then you can inspect b.errors
See https://api.rubyonrails.org/classes/ActiveRecord/RecordInvalid.html
Instead of raising the exception you could do something like
if a.save
redirect_to a
else
render json: {errors: a.errors}