![]()
#Rails Test if a column exists
A really small & simple trick to avoid headaches…
…When you want to test if a model’s column already exists or not.
Use :
- if User.column_names.include?(“is_cool”)
- end
Instead of :
- if User.is_cool?
- end
Because if it’s a boolean column, it will return the same result if the column do not exist and if its value is false… Which is totally different ! In one case the user is not cool, in the other, you do not know !
This case happens often with migrations adding a columns later in a project, having after_save/after_create methods, etc… And when someone need to clone your project the first time, you’ll avoid having crashes on every migrations !