Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails' ActiveRecord, what does a question mark at the end of a method name corresponding to a column do?

If Person is a Rails ActiveRecord class, and name is a table column with a type of string, then Person#name? doesn't seem to correspond to whether or not name is truthy. For example, if name is set to an empty string, the string is truthy, but name? returns false, at least for Rails 3.2.x. What does adding a question mark do?

I tried searching for this, but question marks aren't very googleable, or even symbolhoundable.

An answer to "Using question mark character in Rails/ActiveRecord column name" mentions that ActiveRecord automatically adds question marks to field (column?) names, but there are conflicting comments on what it does.

like image 962
Andrew Grimm Avatar asked Oct 25 '25 17:10

Andrew Grimm


2 Answers

It will return true if a field is present? or not. So an empty string "" will return false.

like image 137
Shannon Avatar answered Oct 28 '25 07:10

Shannon


The question mark methods are similar to present? but not the same. For instance, numeric values will return true if they aren't zero, whereas 0.present? returns true. Here's the line in the Rails source.

like image 38
Clay Shentrup Avatar answered Oct 28 '25 07:10

Clay Shentrup