Ruby - Why this callback function doesn't work

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.

Upvotes: 1

Views: 214

Answers (1)

Jakob S
Jakob S

Reputation: 20145

Your callback is preventing the model from being saved. From http://apidock.com/rails/ActiveRecord/Callbacks:

If the returning value of a before_validation callback can be evaluated to false, the process will be aborted and Base#save will return false. If Base#save! is called it will raise a ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.

When self.closed is not nil your callback returns the value of self.closed.nil? (ie false), thus stopping the save from happening. To prevent this, make sure you return true:

def ensure_default_data
  self.closed = false if self.closed.nil?
  true
end

Upvotes: 6

Related Questions