今天接著昨天的實作
先建立一個 Order model:
$ rails g model Order total_amount:decimal coupon_code:string
在 db/migrate 目錄中找到新建立的 Migration:
class CreateOrders < ActiveRecord::Migration[6.1]
def change
create_table :orders do |t|
t.decimal :total_amount, precision: 8, scale: 2
t.string :coupon_code
t.timestamps
end
end
end
別忘了執行:
$ rails db:migrate
order 也需要一個 controller:
$ rails g controller orders
# OrdersController
class OrdersController < ApplicationController
def new
@order = Order.new
end
def create
@order = Order.new(order_params)
if @order.save
# Apply the coupon discount if a valid coupon code is provided
if params[:coupon_code].present?
books_coupon = BooksCoupon.find_by(code: params[:coupon_code])
if books_coupon&.available?
@order.total_amount = books_coupon.apply_discount(@order.total_amount)
books_coupon.increment!(:used_count)
else
flash[:alert] = 'Invalid or expired coupon code.'
render :new
return
end
end
@order.save
redirect_to root_path, notice: 'Order placed successfully.'
else
render :new
end
end
private
def order_params
params.require(:order).permit(:total_amount, :coupon_code)
end
end
<%= form_with(model: @order, url: orders_path) do |form| %>
<div class="field">
<%= form.label :total_amount %>
<%= form.number_field :total_amount %>
</div>
<div class="field">
<%= form.label :coupon_code %>
<%= form.text_field :coupon_code %>
</div>
<div class="actions">
<%= form.submit 'Place Order' %>
</div>
<% end %>
Rails.application.routes.draw do
resources :books_coupons, only: [:new, :create, :index]
resources :orders, only: [:new, :create]
root 'orders#new'
end
這樣一來一個小小的折價券功能就經由 rails 的 CRUD 建立起來,總之想把 ruby on rails 學好的不二法門就是練熟 CRUD
明天預計來介紹資料驗證,我們明天見!