Skip to content

Instantly share code, notes, and snippets.

@jwo
Created August 11, 2014 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwo/f08b32f372fc6385acfd to your computer and use it in GitHub Desktop.
Save jwo/f08b32f372fc6385acfd to your computer and use it in GitHub Desktop.
TIYA review of relationships
class Order
has_many :line_items
has_many :cupcakes, through: :line_items
def total_price
totals = line_items.map(&:total) # 50, 50, 100
totals.sum
totals.inject(:+)
# total = 0
#
# line_items.each do |li| # 50, 50, 100
# total += li.total
# end
#
# total
end
end
class LineItem
belongs_to :order
belongs_to :cupcake
#quantity
#price
def total
quantity * price
end
end
class Cupcake
has_many :line_items
has_many :orders, through: :line_items
# name
end
--------
# @order
puts @order.id
puts @order.created_at
"your cupcake selections: #{@order.cupcakes.map(&:name).join(", ")}"
@order.line_items.each do |line_item|
print line_item.quantity
print number_to_currency line_item.price
print line_item.cupcake.name
end
puts "total: #{@order.total_price}"
# sum all line_item totals (price * quantity)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment