problem: validation error is not functionning in callback
callback for many-to-many association:
keyword.rb
:before_add => :reject_self_related
def reject_self_related(related_keyword)
if (related_keyword == self)
this does not work:
errors.add(:name, "Relating a keyword to itself is
forbidden!")
raise “Relating a keyword to itself is forbidden!”
end
end
in the keyword.rhtml form:
<%= error_messages_for ‘keyword’ %>
does not display the error message.
what am I doing wrong?
Isabelle wrote:
Hi Isabelle,
First off, is the callback being triggered at all ? If you replace the
whole body with the raise, do you see the exception ?
Second, if you just replace the body with the errors.add, do you see the
error ?
Last, == on Object tests for the exact same Object, I think ActiveRecord
override this to compare ids, if the new item hasn’t yet been saved, the
== method will return false. Perhaps you need to check, say
keyword.text, or whatever the property is that stores the text.
Alan
Alan F. wrote:
Isabelle wrote:
Hi Isabelle,
First off, is the callback being triggered at all ? If you replace the
whole body with the raise, do you see the exception ?
yes. I can catch the exception in the controller and display the
exception message:
keywords_controller.rb
# attempt to add item to list
begin
@keyword.related_keywords<< @related
rescue Exception
# extract error messages from the global variable
# representing the Exception object
flash[:notice] = $!.message
end
Second, if you just replace the body with the errors.add, do you see the
error ?
no, and the object that should not have been saved is saved.
Last, == on Object tests for the exact same Object, I think ActiveRecord
override this to compare ids, if the new item hasn’t yet been saved, the
== method will return false. Perhaps you need to check, say
keyword.text, or whatever the property is that stores the text.
I see your point. In my case the callback is before adding an existing
item to a collection that is defined as a self-referential
has_and_belongs_to_many relation.
Alan F. wrote:
I see your point. In my case the callback is before adding an existing
item to a collection that is defined as a self-referential
has_and_belongs_to_many relation.
I’d reckon that’s the problem then, and would compare the attribute,
rather than the object.
tried it and still the errors.add() is not executed
I see your point. In my case the callback is before adding an existing
item to a collection that is defined as a self-referential
has_and_belongs_to_many relation.
I’d reckon that’s the problem then, and would compare the attribute,
rather than the object.