I have this statement on my model:
class Question
validates :closed, :inclusion => { :in => [false, true] }
before_validation :ensure_default_data
def ensure_default_data
self.closed = false if self.closed.nil?
end
end
When I call:
Question.create
It outputs me:
#<Question id:nil, closed: false>
If I modify the function to this:
def ensure_default_data
self.closed = 0 if self.closed.nil?
end
It works!
Someone has any idea about it and why the first function doesn’t work?
I’m using PostgreSQL and my field is boolean.
Your callback is preventing the model from being saved. From http://apidock.com/rails/ActiveRecord/Callbacks:
When
self.closedis notnilyour callback returns the value ofself.closed.nil?(iefalse), thus stopping the save from happening. To prevent this, make sure you return true: