要使用MySQL和Ruby on Rails開發(fā)一個簡單的在線訂單管理系統(tǒng),需要按照以下步驟進行:
安裝MySQL數(shù)據(jù)庫:在本地或者服務器上安裝MySQL數(shù)據(jù)庫,并創(chuàng)建一個新的數(shù)據(jù)庫用于存儲訂單管理系統(tǒng)的數(shù)據(jù)。
創(chuàng)建Rails應用:使用命令行工具創(chuàng)建一個新的Rails應用。
rails new order_management_system
development:
adapter: mysql2
encoding: utf8
database: your_database_name
username: your_username
password: your_password
host: localhost
port: 3306
rails generate model Order name:string quantity:integer
rails generate model User name:string email:string
rails db:migrate
# app/models/order.rb
class Order < ApplicationRecord
belongs_to :user
end
# app/models/user.rb
class User < ApplicationRecord
has_many :orders
end
rails generate controller Orders
rails generate controller Users
# app/controllers/orders_controller.rb
class OrdersController < ApplicationController
def index
@orders = Order.all
end
def show
@order = Order.find(params[:id])
end
def new
@order = Order.new
end
def create
@order = Order.new(order_params)
if @order.save
redirect_to orders_path
else
render 'new'
end
end
private
def order_params
params.require(:order).permit(:name, :quantity)
end
end
# app/views/orders/index.html.erb
<h1>Orders</h1>
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
</tr>
<% @orders.each do |order| %>
<tr>
<td><%= order.name %></td>
<td><%= order.quantity %></td>
</tr>
<% end %>
</table>
# app/views/orders/show.html.erb
<h1>Order Details</h1>
<p>Name: <%= @order.name %></p>
<p>Quantity: <%= @order.quantity %></p>
# app/views/orders/new.html.erb
<h1>New Order</h1>
<%= form_with model: @order, url: orders_path do |form| %>
<div>
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div>
<%= form.label :quantity %>
<%= form.number_field :quantity %>
</div>
<%= form.submit 'Create Order' %>
<% end %>
Rails.application.routes.draw do
resources :orders
resources :users
end
rails server
現(xiàn)在你應該能夠在瀏覽器中訪問訂單管理系統(tǒng),并進行訂單的創(chuàng)建、查看和列表等操作了。