i did not know that

Jared Carroll

Here’s something I discovered the other day:

ActiveRecord infers model attributes from the database. Each attribute gets a getter, setter, and query method.

A query method? I know this is true for boolean columns but non boolean columns?

class User < ActiveRecord::Base

users (id, name) # schema

def test_should_say_if_it_does_or_does_not_have_a_name_when_sent_name?
  user = User.new
  assert ! user.name?

  user.name = ''
  assert ! user.name?

  user.name = 'name'
  assert user.name?

You get that query method for free for each of your ActiveRecord attributes. From this passing test it looks as if for strings its implemented in terms of String#blank?

This is nice because it can save you an extra message.

if user.name.blank?


if ! user.name?