DEV Community

Robin Vernon
Robin Vernon

Posted on

A Basic guide to Active Record Commands

When transitioning to Ruby’s active record, the commands can be a little long winded and tedious. Here i have provided a cheat sheet to basic AR commands


When working with Active Record and making classes, often we will have to write methods, below are some of the basic methods you will most likely encounter along.

Retrieve a list of all the columns in the table

Create a new entry in the database and saves it

Return all the desired instances of the class from the table

Retrieve an instance from the database by id

Find by any attribute(ie. name)

You can get or set attributes of an instance

save changes to the database

Finds the first instance with the given attributes, or creates a instance with the attributes if one does not exist

Using rake commands can sometimes get a little confusing, especially with the bundle exec prefix, these are the task you’ll likely encounter most

Create migration
bundle exec rake db:create_migration NAME=

bundle exec rake db:migrate

Create Table

create_table :modelName do |t|

      t.string :name

      t.string :genre

      t.integer :age

      t.string :hometown

Enter fullscreen mode Exit fullscreen mode

Check status
bundle exec rake db:migrate:status

bundle exec rake db:rollback

Running a seed file
bundle exec rake db:seed

or to replant with new data
bundle exec rake db:seed:replant

Looping faker gem

Another amazing tool we can use is the faker gem, once we have created our migrations and tables, we can use this gem in the seed file to fill our tables with dummy data. This is particularly useful when wanting to test methods

50.times do

  # create a movie with random data


    title: Faker::Movie.title,

    genre: Faker::Movie.genre,

    ticket_price: rand(0..20) # random number between 0 and 20

Enter fullscreen mode Exit fullscreen mode


Though this isnt everything, hopefully this will help you when diving into ORM!! Happy coding!
check out my github to see how i utilize these:

Top comments (0)