diff --git a/app/controllers/products_controller.rb b/app/controllers/products_controller.rb index 9161b7a..1a4a986 100644 --- a/app/controllers/products_controller.rb +++ b/app/controllers/products_controller.rb @@ -65,6 +65,16 @@ class ProductsController < ApplicationController end end + def who_bought + @product = Product.find(params[:id]) + @latest_order = @product.orders.order(:updated_at).last + if stale?(@latest_order) + respond_to do |format| + format.atom + end + end + end + private # Use callbacks to share common setup or constraints between actions. def set_product diff --git a/app/models/product.rb b/app/models/product.rb index 97bb02f..fa0fb95 100644 --- a/app/models/product.rb +++ b/app/models/product.rb @@ -1,5 +1,6 @@ class Product < ApplicationRecord has_many :line_items + has_many :orders, through: :line_items before_destroy :ensure_not_referenced_by_any_line_item diff --git a/app/views/products/who_bought.atom.builder b/app/views/products/who_bought.atom.builder new file mode 100644 index 0000000..58ea06a --- /dev/null +++ b/app/views/products/who_bought.atom.builder @@ -0,0 +1,40 @@ +atom_feed do |feed| + feed.title "Who bought #{@product.title}" + + feed.updated @latest_order.try(:updated_at) + + @product.orders.each do |order| + feed.entry(order) do |entry| + entry.title "Order #{order.id}" + entry.summary type: 'xhtml' do |xhtml| + xhtml.p "Shipped to #{order.address}" + + xhtml.table do + xhtml.tr do + xhtml.th 'Product' + xhtml.th 'Quantity' + xhtml.th 'Total Price' + end + order.line_items.each do |item| + xhtml.tr do + xhtml.td item.product.title + xhtml.td item.quantity + xhtml.td number_to_currency item.total_price + end + end + xhtml.tr do + xhtml.th 'total', colspan: 2 + xhtml.th number_to_currency \ + order.line_items.map(&:total_price).sum + end + end + + xhtml.p "Paid by #{order.pay_type}" + end + entry.author do |author| + author.name order.name + author.email order.email + end + end + end +end diff --git a/config/routes.rb b/config/routes.rb index 2c68730..280719f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -4,6 +4,9 @@ Rails.application.routes.draw do resources :carts root 'store#index', as: 'store_index' - resources :products + resources :products do + get :who_bought, on: :member + end + # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end