Ruby on Rails Ruby on Rails ActiveRecord & Database Management 2 — Questions and Answers
Question 1: What does `validates :title, presence: true` do in an ActiveRecord model?
- Creates a database constraint
- Ensures the title field is not blank before saving (Correct answer)
- Sets a default value for title
- Encrypts the title field
Correct answer: Ensures the title field is not blank before saving
`validates :title, presence: true` adds a model-level validation that prevents saving if the title attribute is blank or nil.
Question 2: What is a Rails migration's `change` method used for?
- Changing model validations
- Defining reversible database schema changes (Correct answer)
- Updating existing data records
- Changing route definitions
Correct answer: Defining reversible database schema changes
The `change` method defines reversible schema migrations; Rails knows how to automatically reverse operations like `add_column` and `create_table`.
Question 3: Which ActiveRecord query method returns only the first matching record or nil?
- Model.first_where
- Model.find_by (Correct answer)
- Model.select_one
- Model.fetch_first
Correct answer: Model.find_by
`Model.find_by(conditions)` returns the first record matching the given conditions, or nil if none is found.
Question 4: What does `db/schema.rb` represent in a Rails application?
- The SQL queries used to seed data
- A snapshot of the current database schema after all migrations (Correct answer)
- The ActiveRecord model definitions
- The database connection configuration
Correct answer: A snapshot of the current database schema after all migrations
schema.rb is auto-generated by Rails to reflect the current cumulative state of all applied migrations.
Question 5: In ActiveRecord, what does `scope :published, -> { where(published: true) }` define?
- A class method that applies a reusable named query filter (Correct answer)
- A validation for the published field
- A callback that publishes records automatically
- A database index on the published column
Correct answer: A class method that applies a reusable named query filter
A `scope` defines a reusable, chainable query that can be called like `Article.published` to filter records.
Question 6: What is the difference between `destroy` and `delete` in ActiveRecord?
- `destroy` is faster; `delete` runs callbacks
- `destroy` runs model callbacks and dependent associations; `delete` directly removes the DB row (Correct answer)
- `delete` is Rails 6+; `destroy` is legacy
- They are identical in behavior
Correct answer: `destroy` runs model callbacks and dependent associations; `delete` directly removes the DB row
`destroy` triggers before/after callbacks and handles dependent associations, while `delete` issues a direct SQL DELETE without callbacks.
What does `validates :title, presence: true` do in an ActiveRecord model?