0

I have a boolean column called ended. Recently I have changed it to not allow null value, so determining whether it is false will be easier.

However I realized quite a number of places relied on auto casting nil to false. If the object was null it would auto convert to false. After this migration if the object is null then error will occur.

eg:

params.merge!({
  ended: nokogiri_doc.at_css('.foo')
})

I don't want to manually add .present? to each of these statements. Is it possible to preserve the auto conversion when having a null:false column (not allowing null value)?

1 Answer 1

1

In database, change the default value of column ended to 0. You can change it in migration as below:

change_column 'table', 'ended', :boolean, :null => false, :default => 0

Another approach, define a after_initialize callback to set the column to false automaticly:

after_initialize :set_default_false

def set_default_false
  self.ended = false if attribute_present?(:ended) and new_record? or ended.blank?
end
Sign up to request clarification or add additional context in comments.

1 Comment

I used the first approach but null still appear sometime, but I believe the 2nd one should do the trick

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.