I have a model named Tickets that being saved to the database even when
invalid. This is stopping me from using validations to help prevent
duplicate data being saved to the DB. In script/console
I encountered a problem like this before and it turned out to be due to
a callback which was returning false. Unbeknownst to me, if a callback
returns false then the whole chain halts. Do you have any callbacks
that fire before validation, and if so could any of them be returning
false?
I encountered a problem like this before and it turned out to be due to
a callback which was returning false. Unbeknownst to me, if a callback
returns false then the whole chain halts. Do you have any callbacks
that fire before validation, and if so could any of them be returning
false?
Hmm…i only have a after_create callback. Here is my ticket.rb model
Even stranger, i turned on debugger level logging, and i only see one
insertion into the database, yet was getting two database entries (but
again only sometimes).
When i tried writing to a file to help trace down the problem, i haven’t
been able to reproduce the issue since: http://pastie.org/749104
This does throw an error on to_email only if the body and from_email are
also not unique. And this is the error i get when i check the errors on
the duplicate objects in the database
I have tested this validation using rspec, and it behaves correctly…
the whole create/after_create situation isn’t relevant to the question
really. The question is ‘how come something fails validation but has no
errors’.
You’ve got a complicated kind of situation going on with the
attr_accessibles which i don’t really understand. I can see that you’ve
got :to_email in there twice which is wrong but probably not the source
of this particular problem.
You’re saying that the combination of :to_email, :body and :from_email
has to be unique? Maybe that’s the problem but you’d expect to get an
error raised if it wasn’t a unique combination.
Here, you load a record out of the db with Ticket.last, then call valid
on it. Then, you load it out of the db AGAIN, from scratch, with
Ticket.last again. So, it doesn’t have any errors because the current
object hasn’t had .valid called on it: it’s only after calling .valid
that it would have anything in .errors. Anything loaded fresh from the
db will never have any errors.
So, instantiate an object and do all of your stuff with that. BTW, i
usually call errors.full_messages to see the errors. eg