CRUD代表创建, 读取, 更新和删除数据库中的数据。 Active Record自动允许应用程序读取和操作表中存储的数据。
在本教程中, 我们将使用MySQL数据库创建一个Rails CRUD。
步骤1创建一个新的Rails应用程序。
rails new crud
步骤2将目录更改为crud。
cd crud
步骤3转到应用程序中的Gemfile并添加以下内容。
gem 'grape'
步骤4转到应用程序中的config / application.rb文件, 然后添加以下内容。
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
步骤5运行以下命令:
bundle install
步骤6转到app / views / layouts / application.html.erb并将以下行插入head标签。
<
%= stylesheet_link_tag??? 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' %>
<
%= stylesheet_link_tag??? 'https://cdn.datatables.net/s/dt/dt-1.10.10, r-2.0.0/datatables.min.css' %>
步骤7转到app / views / layouts / application.html.erb并将以下行插入< / body> 标记之前。
<
%= javascript_include_tag 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js' %>
<
%= javascript_include_tag 'https://cdn.datatables.net/s/dt/dt-1.10.10, r-2.0.0/datatables.min.js' %>
步骤8在上面的文件中, 将< %= yield%> 替换为以下代码:
<
div class="container">
<
div>
<
% if flash[:notice] %>
<
div>
<
%= flash[:notice] %>
<
/div>
<
% end %>
<
%= yield %>
<
/div>
<
/div>
<
/div>
步骤9转到app / assets / javascripts / application.js并添加加载jQuery DataTable的javascript代码:
var ready = function() {
$('#products').DataTable({
"columnDefs": [
{ "width": "19%", className: "dt-body-center", "targets": -1 }, { "width": "10%", "targets": 0 }, { "width": "7%", "targets": 1 }, { "width": "20%", "targets": 2 }, { "width": "20%", "targets": 3 }, ]
});
}
$(document).ready(ready);
$(document).on('page:load', ready);
步骤10从控制台创建一个控制器。
rails g controller products index show new create edit update destroy
步骤11从控制台创建模型。
rails g model product name:string price:decimal short_description:text full_description:text
步骤12转到app / controllers / products_controller.rb并编写以下代码。
class ProductsController <
ApplicationController
# GET method to get all products from database
def index
@products = Product.all
end
# GET method to get a product by id
def show
@product = Product.find(params[:id])
end
# GET method for the new product form
def new
@product = Product.new
end
# POST method for processing form data
def create
@product = Product.new(product_params)
if @product.save
flash[:notice] = 'Product added!'
redirect_to root_path
else
flash[:error] = 'Failed to edit product!'
render :new
end
end
# GET method for editing a product based on id
def edit
@product = Product.find(params[:id])
end
# PUT method for updating in database a product based on id
def update
@product = Product.find(params[:id])
if @product.update_attributes(product_params)
flash[:notice] = 'Product updated!'
redirect_to root_path
else
flash[:error] = 'Failed to edit product!'
render :edit
end
end
# DELETE method for deleting a product from database based on id
def destroy
@product = Product.find(params[:id])
if @product.delete
flash[:notice] = 'Product deleted!'
redirect_to root_path
else
flash[:error] = 'Failed to delete this product!'
render :destroy
end
end
# we used strong parameters for the validation of params
def product_params
params.require(:product).permit(:name, :price, :old_price, :short_description, :full_description)
end
end
步骤13转到app / models / product.rb并在名称, 价格和描述字段中进行一些验证。
class Product <
ApplicationRecord
validates :name, presence: true
validates :price, presence: true, numericality: {:greater_than =>
0}
validates :short_description, presence: true
end
步骤14转到config / routes.rb并添加:
resources :products
root 'products#index'
步骤14转到config / routes.rb并添加:
resources :products
root 'products#index'
步骤15现在在应用程序文件夹中创建一个名为api的文件夹。在此文件夹中, 创建一个名为product的文件夹。现在, 终于创建了app / api / products / products_api.rb文件并添加以下代码。
module Products
class ProductsAPI <
Grape::API
format :json
desc "Product List", {
:notes =>
<
<
-NOTE
Get All Products
__________________
NOTE
}
get do
Product.all
end
desc "Product By Id", {
:notes =>
<
<
-NOTE
Get Product By Id
__________________
NOTE
}
params do
requires :id, type: Integer, desc: "Product id"
end
get ':id' do
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
error!({ status: :not_found }, 404)
end
end
desc "Delete Product By Id", {
:notes =>
<
<
-NOTE
Delete Product By Id
__________________
NOTE
}
params do
requires :id, type: Integer, desc: "Product id"
end
delete ':id' do
begin
product = Product.find(params[:id])
{ status: :success } if product.delete
rescue ActiveRecord::RecordNotFound
error!({ status: :error, message: :not_found }, 404)
end
end
desc "Update Product By Id", {
:notes =>
<
<
-NOTE
Update Product By Id
__________________
NOTE
}
params do
requires :id, type: Integer, desc: "Product id"
requires :name, type: String, desc: "Product name"
requires :price, type: BigDecimal, desc: "Product price"
optional :old_price, type: BigDecimal, desc: "Product old price"
requires :short_description, type: String, desc: "Product old price"
optional :full_description, type: String, desc: "Product old price"
end
put ':id' do
begin
product = Product.find(params[:id])
if product.update({
name: params[:name], price: params[:price], old_price: params[:old_price], short_description: params[:short_description], })
{ status: :success }
else
error!({ status: :error, message: product.errors.full_messages.first }) if product.errors.any?
end
rescue ActiveRecord::RecordNotFound
error!({ status: :error, message: :not_found }, 404)
end
end
desc "Create Product", {
:notes =>
<
<
-NOTE
Create Product
__________________
NOTE
}
params do
requires :name, type: String, desc: "Product name"
requires :price, type: BigDecimal, desc: "Product price"
optional :old_price, type: BigDecimal, desc: "Product old price"
requires :short_description, type: String, desc: "Product old price" end
post do
begin
product =Product.create({
name: params[:name], price: params[:price], old_price: params[:old_price], short_description: params[:short_description], })
if product.save
{ status: :success }
else
error!({ status: :error, message: product.errors.full_messages.first }) if product.errors.any?
end
rescue ActiveRecord::RecordNotFound
error!({ status: :error, message: :not_found }, 404)
end
end
end
end
步骤16转到config / routes.rb并添加以下代码。
mount Products::ProductsAPI =>
'/api/products'
步骤17在控制台中运行以下命令。
rake db:migrate
步骤18在app / views / products /文件中, 编写以下代码。
index.html.erb
<
!DOCTYPE html>
<
html>
<
body>
<
div class="container">
<
h3>
STOCK LIST<
/h3>
<
div>
<
%= link_to 'Add Product', new_product_path %>
<
/div>
<
br>
<
table border="2">
<
thead>
<
tr>
<
th>
Name<
/th>
<
th>
Price<
/th>
<
th>
Description<
/th>
<
th>
Actions<
/th>
<
/tr>
<
/thead>
<
tbody>
<
% @products.each do |product| %>
<
tr>
<
td>
<
%= product.name %>
<
/td>
<
td>
<
%= product.price %>
<
/td>
<
td>
<
%= truncate(product.short_description, :length =>
75) %>
<
/td>
<
div>
<
td>
<
%= link_to 'Show', product_path(product) %>
<
%= link_to 'Edit', edit_product_path(product) %>
<
%= link_to 'Delete', product_path(product), method: :delete %>
<
/div>
<
/td>
<
/tr>
<
% end %>
<
/tbody>
<
/table>
<
/div>
<
/body>
<
/html>
new.html.erb
<
div class="container">
<
%= form_for @product, url: {action: :create} do |f| %>
<
div>
<
h3>
Add a Product<
/h3>
<
/div>
<
div>
<
p>
<
%= "<
div>
#{@product.errors.full_messages.first}<
/div>
".html_safe if @product.errors.any? %>
<
div>
<
label>
Product Name<
/label>
<
%= f.text_field :name %>
<
/div>
<
div>
<
label>
Price<
/label>
<
%= f.text_field :price %>
<
/div>
<
div>
<
label>
Description<
/label>
<
%= f.text_field :short_description %>
<
/div>
<
/p>
<
/div>
<
div>
<
%= link_to 'Back', { controller: 'products', action: 'index'} %>
<
%= f.submit 'Create Product' %>
<
/div>
<
% end %>
<
/div>
edit.html.erb
< div class =” container” > < %= form_for @product, 网址:{action::update} do | f | %> < h3> 添加产品< / h3> < %=” < div> #{@ product.errors.full_messages.first} < / div> ” 。html_safe, 如果@ product.errors.any? %> < p> < div> < label> 产品名称< / label> < %= f.text_field:name%> < / div> < div> < label> Price < / label> < %= f.text_field:price %> < / div> < div> < label> 描述< / label> < %= f.text_field:short_description%> < / div> < / p> < div> < %= link_to’ Back’ , {controller:’ 产品” , 操作:’ index’ }%> < %= f。提交’ Update Product’ %> < / div> < %end%> < / div>
show.html.erb
<
div class="container">
<
h3>
Add a Product<
/h3>
<
div>
<
label>
Product Name<
/label>
<
%= @product.name %>
<
/div>
<
div>
<
label>
Price<
/label>
<
%= @product.price %>
<
/div>
<
div>
<
label>
Description<
/label>
<
%= @product.short_description %>
<
/div>
<
div>
<
%= link_to 'Back', { controller: 'products', action: 'index'} %>
<
/div>
<
/div>
步骤19从命令行启动服务器。
rails s
步骤20在本地主机上运行该应用程序。
localhost:3000/products
将出现以下页面。在这里, 我们已经在表中插入了一些数据。
![Ruby on Rails CRUD操作图解](http://www.srcmini.com/wp-content/uploads/2020/03/ruby-on-rails-crud1.png)
文章图片
插入资料
![Ruby on Rails CRUD操作图解](http://www.srcmini.com/wp-content/uploads/2020/03/ruby-on-rails-crud2.png)
文章图片
要插入数据, 请单击以上快照中所示的” 添加产品” 。如下所示填写详细信息。
![Ruby on Rails CRUD操作图解](http://www.srcmini.com/wp-content/uploads/2020/03/ruby-on-rails-crud3.png)
文章图片
读取资料
要读取数据, 请单击操作显示。在这里, 我们将单击” 跳伞表演” 动作。
![Ruby on Rails CRUD操作图解](http://www.srcmini.com/wp-content/uploads/2020/03/ruby-on-rails-crud4.png)
文章图片
更新资料
要更新数据, 请单击” 编辑操作” 。在这里, 我们将编辑从男式正装衬衫到女式正装衬衫的衬衫描述。
![Ruby on Rails CRUD操作图解](http://www.srcmini.com/wp-content/uploads/2020/03/ruby-on-rails-crud5.png)
文章图片
![Ruby on Rails CRUD操作图解](http://www.srcmini.com/wp-content/uploads/2020/03/ruby-on-rails-crud6.png)
文章图片
删除资料
要删除数据, 请单击” 删除” 操作。在这里, 我们将从上表中删除产品牛仔裤。
![Ruby on Rails CRUD操作图解](http://www.srcmini.com/wp-content/uploads/2020/03/ruby-on-rails-crud7.png)
文章图片
下载
【Ruby on Rails CRUD操作图解】下载此示例
推荐阅读
- Rails多种过滤器用法实例
- Rails文件上传实例详细图解
- Rails 3种缓存用法和实例
- Ruby on Rails 5 Hello World示例
- Rails脚本工具使用介绍
- Ruby on Rails RVM版本管理用法
- Ruby on Rails MVC开发基本概念
- Rails IDE或编辑器介绍
- Ruby Active Record解释和用法例子