| @@ -65,6 +65,16 @@ class ProductsController < ApplicationController | |||||
| end | end | ||||
| 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 | private | ||||
| # Use callbacks to share common setup or constraints between actions. | # Use callbacks to share common setup or constraints between actions. | ||||
| def set_product | def set_product | ||||
| @@ -1,5 +1,6 @@ | |||||
| class Product < ApplicationRecord | class Product < ApplicationRecord | ||||
| has_many :line_items | has_many :line_items | ||||
| has_many :orders, through: :line_items | |||||
| before_destroy :ensure_not_referenced_by_any_line_item | before_destroy :ensure_not_referenced_by_any_line_item | ||||
| @@ -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 | |||||
| @@ -4,6 +4,9 @@ Rails.application.routes.draw do | |||||
| resources :carts | resources :carts | ||||
| root 'store#index', as: 'store_index' | 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 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html | ||||
| end | end | ||||