Skip to content

Latest commit

 

History

History
61 lines (42 loc) · 1.29 KB

solutions.md

File metadata and controls

61 lines (42 loc) · 1.29 KB

Practice Associations

One-to-Many Challenges

Solutions for Rails console portions:

  1. Create an item:
i = Item.create(name: "lamp", description: "desk lamp", price: 2000)
  1. Create an order:
o = Order.create
  1. Associate item to order:
o.items << i
  1. For one order, iterate through each of its items and print the item details to the console:
o.items.each do |item|
  puts "#{item.name}: #{item.description}, $#{item.price}"
end
  1. Map each item in your database to its name:
Item.all.map { |item| item.name }
# which can be shortened to
Item.all.map(&:name)

Stretch: Select only the items in an order that are less than a certain price:

o.items.where("price < ?", 3000)

Many-To-Many Challenges

Solutions for Rails console portions:

Create and use actor, movie, and association:

arnold = Actor.create(first_name: "Arnold", last_name: "Schwarzenegger")
terminator = Movie.create(title: "The Terminator", description: "science fiction film", year: 1984)
terminator.actors << arnold

# check associations
terminator.actors
arnold.movies