In keeping with Ruby's idiom of using a question mark in boolean methods (e.g. person.is_smart?
), I'd like to do the same for an ActiveRecord field in Rails:
rails generate model Person is_smart?:boolean
I haven't actually run the above statement. I assume that database fields can't have a question mark in them. Will rails deal with this appropriately? Is the best practice to simply leave question marks off of models?
Using Rails 3.2.8
It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value). The question mark is a valid character at the end of a method name.
Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns. Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id , order_id ).
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Rails will automatically generate the method smart?
if there is a field named 'smart'
.
One "gotcha" to be aware of if you happen to use :enum
in your model, since this stores the value as an integer. The question mark attr method provided by active record expects to evaluate 0 or 1 as false / true respectively in the database. For example:
class Person enum mood: ['happy', 'sad', 'bored'] end p = Person.new(mood: 'happy') # this would store mood as 0 in db p.mood? #=> false p.mood = 'sad' # saves as 1 in db p.mood? #=> true p.mood = 'bored' # saves as 2 in db p.mood? #=> true
to see how this method works, see rails source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With