Ruby on Rails Ruby on Rails ActiveRecord & Database Management 1 — Questions and Answers
Question 1: What is ActiveRecord in Ruby on Rails?
- A caching library
- The ORM layer that maps Ruby objects to database tables (Correct answer)
- A routing module
- A background job framework
Correct answer: The ORM layer that maps Ruby objects to database tables
ActiveRecord is Rails' ORM (Object-Relational Mapping) that represents database tables as Ruby classes and rows as objects.
Question 2: Which Rails command generates a new database migration file?
- rails db:new
- rails generate migration AddTitleToArticles (Correct answer)
- rails migrate:create
- rails db:schema
Correct answer: rails generate migration AddTitleToArticles
`rails generate migration MigrationName` creates a timestamped migration file in db/migrate/ for database schema changes.
Question 3: What does `rails db:migrate` do?
- Rolls back all migrations
- Runs all pending migration files to update the database schema (Correct answer)
- Exports the database to a file
- Seeds the database with test data
Correct answer: Runs all pending migration files to update the database schema
`rails db:migrate` executes all pending migration files in chronological order to apply schema changes to the database.
Question 4: In ActiveRecord, what does `has_many :comments` in an Article model define?
- A validation that requires comments
- A one-to-many association where an article has multiple comments (Correct answer)
- A method that counts comments
- A database index on the comments table
Correct answer: A one-to-many association where an article has multiple comments
`has_many :comments` establishes a one-to-many association, allowing `article.comments` to retrieve all comments for that article.
Question 5: What is the purpose of `belongs_to :article` in a Comment model?
- To create the articles table
- To define the inverse side of a has_many relationship, requiring an article_id foreign key (Correct answer)
- To validate that comments belong to an article class
- To generate a route for comments under articles
Correct answer: To define the inverse side of a has_many relationship, requiring an article_id foreign key
`belongs_to :article` declares the Comment as the child side of the relationship and expects an `article_id` column in the comments table.
Question 6: Which ActiveRecord method retrieves all records from a table?
- Model.find_all
- Model.all (Correct answer)
- Model.select(*)
- Model.fetch
Correct answer: Model.all
`Model.all` returns an ActiveRecord::Relation containing all records for that model's corresponding database table.
What is ActiveRecord in Ruby on Rails?