###開発環境
- MacOS X 10.11 El Capitan
- Ruby 2.3.1
- Ruby on Rails 4.2.6
###発生している問題・エラーメッセージ
ECサイトを作っています。現在、下記の画像のようにショッピングカートを作っておりまして、あとは合計金額を出力するのみなのですが、どうやって足し合わせていけばいいのかわからず止まっています。いい方法があれば教えて頂ければ、と思います。すでに各商品の小計(値段×個数)は出力できているので、あとは商品ごとの小計を足し合わせていくだけの状態にはなっています。
このビューのソースは下記のとおりです。
html
1# app/views/products/content.html.erb 2 3<h1>カートの中身</h1> 4 5<table border="1"> 6 <tr> 7 <td>商品番号</td> 8 <td>値段</td> 9 <td>商品説明</td> 10 <td>画像</td> 11 <td>個数</td> 12 <td>小計</td> 13 </tr> 14 <% session[:cart].each do |key, value| %> 15 <tr> 16 <td><%= session[:cart]["#{key}"]["id"] %></td> 17 <td><%= session[:cart]["#{key}"]["price"] %></td> 18 <td><%= session[:cart]["#{key}"]["description"] %></td> 19 <td><%= link_to image_tag(Product.find("#{key}").image.url), { :controller => :products, :action => :show, :id => Product.find("#{key}").id }%> </td> 20 <td><%= session[:item]["#{key}"] %></td> 21 <td><%= session[:cart]["#{key}"]["price"].to_i * session[:item]["#{key}"].to_i %></td> 22 </tr> 23 <% end %> 24 合計金額 25</table>
以下、補足です。
- productsコントローラーのソースです。
ruby
1# app/controllers/products_controller.rb 2 3class ProductsController < ApplicationController 4 5 def index 6 @product_all = Product.all 7 end 8 9 def new 10 @product_new = Product.new 11 end 12 13 def create 14 Product.create(product_params_create) 15 redirect_to :action => "index" 16 end 17 18 def show 19 @product = Product.find(params[:id]) 20 session[:cart] ||= {} 21 session[:cart]["#{params[:id]}"] = Product.find(params[:id]) 22 end 23 24 def add 25 session[:item] ||= {} 26 session[:item]["#{params[:id]}"] = params[:item] 27 end 28 29 def content 30 end 31 32 def destroy 33 product = Product.find(params[:id]) 34 product.destroy 35 end 36 37 def edit 38 @product_edit = Product.find(params[:id]) 39 end 40 41 def update 42 @product_update = Product.find(params[:id]) 43 @product_update.update(product_params_update) 44 redirect_to :action => "index" 45 end 46 47 48private 49 def product_params_create 50 params.require(:product).permit(:price, :description, :image) 51 end 52 53 def product_params_update 54 params.permit(:price, :description, :image) 55 end 56 57end
- productモデルのソースです。
ruby
1# app/models/product.rb 2 3class Product < ActiveRecord::Base 4 mount_uploader :image, ImageUploader 5end 6
以上です。どうぞご教示ください。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/05 23:59