Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using question mark character in Rails/ActiveRecord column name

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

like image 716
at. Avatar asked Sep 24 '12 05:09

at.


People also ask

What is the question mark in Ruby method?

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.

What is ActiveRecord naming convention?

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 ).

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is Ruby ActiveRecord?

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.


2 Answers

Rails will automatically generate the method smart? if there is a field named 'smart'.

like image 165
cdesrosiers Avatar answered Sep 21 '22 18:09

cdesrosiers


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

like image 24
lacostenycoder Avatar answered Sep 22 '22 18:09

lacostenycoder