I'm building an e-commerce website. In the buyer profile view(users/show.html.erb), i'm try to sum his number of purchases. But i don't know how.
Here is my code:
views/users/show.html.erb:
<h2><%= @user.first_name %> <%= @user.last_name %></h2>
<p>
<strong>Number of purchases:</strong>
<% Sale.where(user_id: @user.id).each do |sale| %>
<%#= sale.product.sum(:id) %>
<% end %>
</p>
<h4>Products purchased by <%= @user.first_name + " " + @user.last_name%></h4>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<% Sale.where(user_id: @user.id).each do |sale| %>
<tr>
<td><%= sale.product.title %></td>
<td><%= sale.product.description %></td>
<td><%= sale.product.price %></td>
<td>
<%= link_to image_tag(sale.product.image, :alt => sale.product.title, class:"img-responsive", style:'width: 100px; height: 100px;'), '/products/' + sale.product.id.to_s %>
</td>
</tr>
<% end %>
</tbody>
</table>
db/schema.rb:
create_table "sales", force: :cascade do |t|
t.integer "product_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "sales", ["product_id"], name: "index_sales_on_product_id"
add_index "sales", ["user_id"], name: "index_sales_on_user_id"
sales_controller.rb :
class SalesController < ApplicationController
before_action :set_sale, only: [:show, :edit, :update, :destroy]
before_filter :require_user
before_action :require_admin, only: [:index]
# GET /sales
# GET /sales.json
def index
@sales = Sale.all
end
# GET /sales/1
# GET /sales/1.json
def show
end
# GET /sales/new
def new
@sale = Sale.new
end
# GET /sales/1/edit
def edit
end
# POST /sales
# POST /sales.json
def create
@sale = Sale.new(sale_params)
@sale.product_id = params[:product_id]
@sale.user_id = current_user.id
@user = @sale.user
respond_to do |format|
if @sale.save
@user.save
format.html { redirect_to '/', notice: 'Your purchase has been registered !' }
format.json { render :show, status: :created, location: @sale }
else
format.html { render :new }
format.json { render json: @sale.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_sale
@sale = Sale.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def sale_params
params.permit(:product_id, :user_id)
end
end
end