https://stackoverflow.com/questions/302782/rails-how-do-i-check-if-a-column-has-a-value
I am giving a very detailed answer to this Question "How do I check if a column has a value?".
First of all, it is important to note that an attribute can have four kinds of values in it.
- nil value i.e "nil" stored in the database
- empty value i.e "" an empty string with no spaces
- empty string with spaces " ".
- value present in database i.e a non-empty string.
Here is the detail behavior of all the present methods(Ruby 2.2.2) that could be used in this case.
First Method: .empty?
For nil value => Throws an exception
2.2.2 :037 > object.attribute => nil 2.2.2 :025 > object.attribute.empty? NoMethodError: undefined method `empty?' for nil:NilClass
For empty value i.e "" an empty string with no spaces
2.2.2 :037 > object.attribute => "" 2.2.2 :025 > object.attribute.empty? true
empty string with spaces " ".
2.2.2 :041 > object.attribute => " " 2.2.2 :042 > object.attribute.empty? => false
value present in database i.e a non-empty string.
2.2.2 :045 > object.attribute => "some value" 2.2.2 :046 > object.attribute.empty? => false
Second Method: .nil?
nil value i.e "nil" stored in the database
2.2.2 :049 > object.attribute => nil 2.2.2 :050 > object.attribute.nil? => true
empty value i.e "" an empty string with no spaces
2.2.2 :053 > object.attribute => "" 2.2.2 :054 > object.attribute.nil? => false
empty string with spaces " ".
2.2.2 :057 > object.attribute => " " 2.2.2 :058 > object.attribute.nil? => false
value present in database i.e a non-empty string.
2.2.2 :061 > object.attribute => "some value" 2.2.2 :062 > object.attribute.nil? => false
Third Method: .blank?
nil value i.e "nil" stored in the database
2.2.2 :065 > object.attribute => nil 2.2.2 :066 > object.attribute.blank? => true
empty value i.e "" an empty string with no spaces
2.2.2 :069 > object.attribute => "" 2.2.2 :070 > object.attribute.blank? => true
empty string with spaces " ".
2.2.2 :073 > object.attribute => " " 2.2.2 :074 > object.attribute.blank? => true
value present in database i.e a non-empty string.
2.2.2 :075 > object.attribute => "some value" 2.2.2 :076 > object.attribute.blank? => false
Fourth Method: .present?
nil value i.e "nil" stored in the database
2.2.2 :088 > object.attribute => nil 2.2.2 :089 > object.attribute.present? => false
empty value i.e "" an empty string with no spaces
2.2.2 :092 > object.attribute => "" 2.2.2 :093 > object.attribute.present? => false
empty string with spaces " ".
2.2.2 :096 > object.attribute => " " 2.2.2 :097 > object.attribute.present? => false
value present in database i.e a non-empty string.
2.2.2 :100 > object.attribute => "some value" 2.2.2 :101 > object.attribute.present? => true
You can use either of the four depending upon the situation you face.
Thanks