HomeToolsAbout

Rails Console

ActiveRecord Models

You can access the models in Rails console directly

# straightforward model names > User.first # grabs the first user record # model names may be different ## some model names may not be as straightward. In db, it may show up as `accounts` table, but the model may have a completely different name class AccountManagement::Account < Rails::ApplicationRecord

Finding the association

> User.last.account # calls account record association on User # in the model, determine the association belongs_to :account, class_name: AccountManagement::Account.name, optional: true

find method only works with an id, use where for other filtering types.

# finding the record to modify ## you have to use first when using where > m = Meme.where(:title => 'Balloon frihgtens cat').first # assignment of new value to the record attribute > m.title = 'Balloon frightens cat' # save the modification > m.save

However, use find when modifying the data. Since it's unique record.

AccountManagement::Account.find(1) AccountManagement::Account.find(1).someAttribute = newValue AccountManagement::Account.find(1).save! AccountManagement::Account.find(1).reload

Alternatively, you can call save with parameter to define the new value:

AccountManagement::Account.last.save!( { :automatically_approve_employee_access_requests => false } )

Programmatically find all associations in existence

# one-liner for finding the foreign key fields model_class_name.reflect_on_all_associations(:belongs_to).map(&:foreign_key) # finding all associations; asc being association asc = model_class_name.reflect_on_all_associations(:belongs_to) # finding foreign key column name; fk being foreign key asc_fk = asc.map(&:foreign_key)

Time

When adjusting time, using Time.now will assign current time.

new_time = Time.now
AboutContact