Web Development

Having fun with ActiveRecord.

class Account < ActiveRecord::Base
  attr_accessible :name,
    :notes,
    :photo,
    :corporate_name,
    :corporate_address,
    :email,
    :phone_number,
    :website
end

Getting attributes of a new ActiveRecord object

rails console
[1] pry(main)> Account.new.attributes
=> {"id"=>nil,
 "name"=>nil,
 "notes"=>nil,
 "status"=>nil,
 "created_at"=>nil,
 "updated_at"=>nil,
 "photo_file_name"=>nil,
 "photo_content_type"=>nil,
 "photo_file_size"=>nil,
 "photo_updated_at"=>nil,
 "corporate_name"=>nil,
 "corporate_address"=>nil,
 "email"=>nil,
 "phone_number"=>nil,
 "website"=>nil,
 "is_active"=>true}

We get blanks on most properties without default values.

Getting attributes of an existing ActiveRecord object

Account.first.attributes
Account Load (39.3ms)  SELECT "accounts".* FROM "accounts" LIMIT 1
=> {"id"=>1,
 "name"=>"Golden Arches",
 "notes"=>"Golden Arches FTW!",
 "status"=>nil,
 "created_at"=>Mon, 02 Dec 2013 09:52:57 UTC +00:00,
 "updated_at"=>Mon, 02 Dec 2013 09:52:57 UTC +00:00,
 "photo_file_name"=>"McDelivery.jpg",
 "photo_content_type"=>"image/jpeg",
 "photo_file_size"=>22492,
 "photo_updated_at"=>Mon, 02 Dec 2013 09:52:57 UTC +00:00,
 "corporate_name"=>"Philippines",
 "corporate_address"=>"ga@goldenarches.com",
 "email"=>"12345678",
 "phone_number"=>"12345678",
 "website"=>"http://www.mcdonals.com.ph",
 "is_active"=>true}

We get all the properties of the existing record.

Attributes when only certain fields are selected

Account.select('name').first.attributes
  Account Load (0.5ms)  SELECT name FROM "accounts" LIMIT 1
=> {"name"=>"Golden Arches"}

Only the selected fields are received by the attributes method.