学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails5.1 | 23 | Webアプリケーション開発 | 買い物カートの合計を表示させる

<<前  [TOP]  次>>


カート全体の合計価格を実装します。
まずは「line_item(品目)」の合計を出します。
line_itemモデルの「line_item.rb」ファイルを以下のように編集します。


【app/models/line_item.rb】

class LineItem < ActiveRecord::Base

	belongs_to :good
	belongs_to :cart

	def total_price
		good.price * quantity
	end

end

line_itemの合計を出す「total_price」メソッドを追記しています。


次にカート全体の合計金額を出す「total_price」メソッドをcartモデルに記述します。
これにはRailsの「sum()」メソッドを利用します。
cartモデルの「cart.rb」ファイルを以下のように編集します。


【app/models/cart.rb】

class Cart < ActiveRecord::Base

	has_many :line_items, dependent: :destroy

	def add_good(good_id)

		current_item = line_items.find_by_good_id(good_id)

		if current_item
			current_item.quantity += 1
		else
			current_item = line_items.build(good_id: good_id)
		end
		current_item

	end

	def total_price
		line_items.to_a.sum { |item| item.total_price }
	end

end

line_itemモデルで追記した「total_price」を利用してその合計を計算しています。
ここでも同じ「 total_price」という名前にしました。


最後にcartsのshowビューの編集をします。


【app/views/carts/show.html.erb】

<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<br>
<h1>Railsはじめてマート</h1>
<h2>   カートに追加された商品</h2>
<br>
<%= button_to 'カートを空にする', @cart, method: :delete, data: {confirm: 'カートを空にして本当によろしいですか?'}, class: 'fbtn' %>
<br>
<table>
	<tr>
		<th></th>
		<th>商品名</th>
		<th>価格</th>
		<th>数量</th>
		<th>合計</th>

	</tr>
		<% @cart.line_items.each do |item| %>
		<tr>
			<td text-align:center;><img height="80" src="<%=h item.good.image_url %>"/></td>
			<td text-align:center;><font size="4"><%= item.good.title %></font></td>
			<td text-align:center;><font size="4"><%= (item.good.price).to_i %></font></td>
			<td text-align:center;><font size="4"><%= item.quantity %></font></td>
			<td text-align:center;><font size="4"><%= (item.total_price).to_i %></font></td>
		</tr>
		<% end %>

		<tr>
			<td colspan="5"><font size="5">総計:<%= (@cart.total_price).to_i %></font></td>
		</tr>

</table>
<br>
<span>  </span><%= link_to '買い物を続ける', market_path, :class => 'btn' %><span>



カートの合計金額を表示できるようになりました。



↓↓クリックして頂けると励みになります。


<<前  [TOP]  次>>