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
Classes
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.
.column_names
Retrieve a list of all the columns in the table
.create
Create a new entry in the database and saves it
.all
Return all the desired instances of the class from the table
.find
Retrieve an instance from the database by id
.find_by
Find by any attribute(ie. name)
.Attr_accessors
You can get or set attributes of an instance
#save
save changes to the database
.Find_or_create_by
Finds the first instance with the given attributes, or creates a instance with the attributes if one does not exist
Rake
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=
Migrate
bundle exec rake db:migrate
Create Table
create_table :modelName do |t|
t.string :name
t.string :genre
t.integer :age
t.string :hometown
end
Check status
bundle exec rake db:migrate:status
Rollback
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
Movie.create(
title: Faker::Movie.title,
genre: Faker::Movie.genre,
ticket_price: rand(0..20) # random number between 0 and 20
)
end
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:
https://github.com/robinlashae1
Top comments (0)