Rails With DB 2
Rails With DB 2
stock (integer). Describe the steps required to update the model, modify the
database schema, and verify the changes.
Step 1: Generate a Migration to Add the Attribute: Use the Rails generator to
create a migration file that adds the stock attribute to the Product model:
rails generate migration AddStockToProducts stock:integer
Step 2: Run the Migration: Apply the migration to update the database schema with
the new column:
rails db:migrate
Step 3: Verify the Update: Open the Rails console to check if the Product model now
includes the stock attribute. Run:
product = Product.new(name: "Sample Product", price: 10.0, stock: 100)
puts product
Describe how you would use Rails migrations to remove an unnecessary attribute
description (string) from an existing Product model. Include steps to create the
migration and verify the changes.
Generate the Migration to Remove the Attribute: Create a migration to remove the
description column from the products table:
rails generate migration RemoveDescriptionFromProducts description:string
Run the Migration: Apply the migration to update the database schema and remove the
description column:
rails db:migrate
Verify the Change: Open the Rails console and check the Product model to confirm
that the description column has been removed:
Product.column_names
You have created a Rails model Order with attributes customer_name (string) and
total_amount (float). Describe how to create and interact with records in this
model, including adding, updating, and retrieving records using the Rails console.
Create:
order = Order.create(customer_name: "Raja", total_amount: 150.0)
Read:
orders = Order.all
puts orders
Update:
order = Order.find(1)
order.update(total_amount: 200.0)
Delete:
order = Order.find(1)
order.destroy