I have problems displaying error_messages.html.erb partial when building custom validation.
I have for instance, a form to make a transaction, which starts like:
<%= form_for @transaction do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
I have a validation which prevents a user from making a transaction with himself:
validate :self_transaction_not_possible
with
def self_transaction_not_possible
bel = Belonging.find_by_id(self.belonging.id)
unless bel.nil?
if self.user_id == bel.user_id
errors.add(:base, "You cannot perform a transaction with yourself")
end
end
end
Then I ran such an example in the browser (initiate a transaction on a belonging I own), and I placed a debugger inside self_transaction_not_possible. I checked that the validation happens, and indeed, inside the debugger, I see that typing: self.errors.full_messages give me my error message, so validation seems to be performed…
I would then have expected, as the object was not valid, that the error message would appear in my view, but no … putting the debugger inside the error_messages.html.erb partial showed me that object.errors.any remains == {} :-/ …
The user is then redirected towards the page it should see when the saving process fails (validation has been performed correctly), but he never sees the error message …
Am I missing something obvious ? …
OK … the reason it failed was because I was doing a REDIRECT_TO in the controller when the transaction was not being saved, thereby deleting the
@transaction.errorsvector …Changing this to a
render :template => 'transactions/edit'solved my issue ..Of course, it was hard to guess looking at the question :-/ …