简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM