In Rails, what is the main reason models represent data?
Think about where the app keeps and organizes information.
Models in Rails are designed to represent and manage the data and business rules of the application. They interact with the database and hold the logic related to the data.
Consider this Rails code:
user = User.new(name: 'Alice')
What does this code do?
Think about when data is saved to the database.
User.new creates a new instance of the User model in memory. It does not save it to the database until you call save.
Given this Rails code:
user = User.new(name: 'Bob') saved = user.save puts saved
What will be printed?
Think about what save returns when successful.
The save method returns true if the model was saved successfully to the database.
Which of these Rails model definitions correctly adds a validation for presence of a name?
class User < ApplicationRecord # validation here end
Look for the correct Rails validation syntax.
The correct syntax to validate presence is validates :name, presence: true. Option A is deprecated syntax, and B and D are incorrect.
Given this model:
class Product < ApplicationRecord
validates :price, numericality: { greater_than: 0 }
end
product = Product.new(price: -5)
product.save!What error will this code raise?
Think about what happens when validations fail and save! is called.
The save! method raises ActiveRecord::RecordInvalid if validations fail, such as when price is less than or equal to zero.