Skip to content

Commit

Permalink
Add Order Purchase Functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
mathiasUCSB committed Nov 15, 2024
1 parent efdb152 commit ad9e953
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 2 deletions.
27 changes: 27 additions & 0 deletions app/controllers/item_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,31 @@ def handle_create_listing
render :create_listing_form, status: :unprocessable_entity
end
end

def show_listing
@item = Item.find(params[:id])
end

def create_order
# Ensure the user is logged in
unless session[:user]
redirect_to login_path and return
end

# Find the item to be ordered
@item = Item.find(params[:id])

# Create a new order with item, user, and quantity parameters
@order = Order.new(
item: @item,
user: User.find(session[:user]["id"]),
quantity: params[:quantity]
)

if @order.save
redirect_to item_path(@item), notice: "Order placed successfully!"
else
redirect_to item_path(@item), alert: @order.errors.full_messages.join(", ")
end
end
end
4 changes: 2 additions & 2 deletions app/views/item/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@
<% @items.each do |item| %>
<li>
<div class="item">
<h2><%= item.name %></h2>
<h2><%= link_to item.name, item_path(item) %></h2>
<p><strong>Description:</strong> <%= item.description %></p>
<p><strong>Price:</strong> <%= number_to_currency(item.price) %></p>
<p><strong>Seller:</strong> <%= item.user.username %></p>
<p><strong>Rating:</strong> TODO</p>
<p><strong>Reviews:</strong> TODO</p>
</div>
</li>
<% end %>
Expand Down
23 changes: 23 additions & 0 deletions app/views/item/show_listing.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<h1><%= @item.name %></h1>
<p><strong>Description:</strong> <%= @item.description %></p>
<p><strong>Price:</strong> <%= number_to_currency(@item.price) %></p>
<p><strong>Seller:</strong> <%= @item.user.username %></p>

<% if session[:user] %>
<%= form_with url: create_order_path(@item), local: true do |form| %>
<div>
<%= form.label :quantity, "Quantity" %>
<%= form.number_field :quantity, min: 1, value: 1 %>
</div>
<%= form.submit "Place Order" %>
<% end %>

<% if flash[:notice] %>
<p class="notice-message"><%= flash[:notice] %></p>
<% end %>

<% else %>
<p>Please <a href="<%= login_path %>">log in</a> to place an order.</p>
<% end %>

<p><strong>Reviews:</strong> </p>
3 changes: 3 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@

get "create_listing" => "item#create_listing_form"
post "create_listing" => "item#handle_create_listing"

get "item/:id" => "item#show_listing", as: :item
post "item/:id/order" => "item#create_order", as: :create_order
end

0 comments on commit ad9e953

Please sign in to comment.