如何使用MySQL和Ruby on Rails開發一個簡單的線上投訴系統
如何使用MySQL和Ruby on Rails開發一個簡單的線上投訴系統
引言:
隨著網路的普及和資訊傳播的迅速,人們對於服務品質的要求也越來越高。線上投訴系統可以幫助企業有效率地處理使用者投訴,改善服務品質。本文將介紹如何使用MySQL和Ruby on Rails來開發一個簡單的線上投訴系統,並提供相應的程式碼範例。
- 建立Rails專案和資料庫
首先,確保你已經安裝了Ruby on Rails和MySQL。在命令列中執行以下命令建立一個新的Rails專案:
$ rails new complaint_system $ cd complaint_system
接下來,設定資料庫連線資訊。開啟config/database.yml文件,依照你的資料庫配置,修改development和test環境的對應配置。如下所示:
default: &default adapter: mysql2 encoding: utf8 pool: 5 username: your_username password: your_password socket: /tmp/mysql.sock host: localhost development: <<: *default database: complaint_system_development test: <<: *default database: complaint_system_test
然後,在命令列中執行以下命令建立資料庫:
$ rake db:create
- 建立投訴模型
在Rails中,我們使用模型來與資料庫交互。在命令列中執行以下指令建立一個名為Complaint的模型:
$ rails generate model Complaint title:string content:text $ rake db:migrate
這會建立一個Complaint模型,並在資料庫中建立一個complaints表,其中包含title和content欄位。
- 寫控制器和檢視
在命令列中執行下列指令建立一個名為Complaints的控制器:
$ rails generate controller Complaints
然後,在app/controllers/ complaints_controller.rb中編寫下列程式碼:
class ComplaintsController < ApplicationController def index @complaints = Complaint.all end def new @complaint = Complaint.new end def create @complaint = Complaint.new(complaint_params) if @complaint.save redirect_to complaints_path, notice: '投诉成功提交' else render :new end end private def complaint_params params.require(:complaint).permit(:title, :content) end end
在app/views/complaints目錄下建立index.html.erb和new.html.erb視圖文件,分別編寫以下程式碼:
index .html.erb:
<h1>投诉列表</h1> <% @complaints.each do |complaint| %> <h2><%= complaint.title %></h2> <p><%= complaint.content %></p> <% end %>
new.html.erb:
<h1>提交投诉</h1> <%= form_with(model: @complaint, url: complaints_path) do |form| %> <%= form.label :title %> <%= form.text_field :title %> <%= form.label :content %> <%= form.text_area :content %> <%= form.submit '提交' %> <% end %>
- 設定路由
開啟config/routes.rb文件,在其中新增以下程式碼:
Rails.application.routes.draw do resources :complaints, only: [:index, :new, :create] root 'complaints#index' end
這會設定Complaints控制器的路由,使其對應的action可以正常存取。
- 執行應用程式
現在,你可以透過執行以下命令啟動Rails應用程式:
$ rails server
然後,在瀏覽器中存取http://localhost :3000,你將會看到投訴系統的首頁。點擊"提交投訴"連結可以訪問投訴表單頁面,填寫表單並提交投訴。點擊"投訴清單"連結可以查看已提交的投訴。
結論:
本文介紹如何使用MySQL和Ruby on Rails開發一個簡單的線上申訴系統。透過建立模型、控制器和視圖,並配置適當的路由,我們實現了一個具有基本功能的投訴系統。在實際開發中,你可以根據具體需求進一步優化和擴展該系統。
以上是完整的程式碼範例,希望對你能有所幫助。
以上是如何使用MySQL和Ruby on Rails開發一個簡單的線上投訴系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

如何修復 MySQL 8.4 上的 mysql_native_password 未載入錯誤
