📜  Ruby on Rails CRUD

📅  最后修改于: 2021-01-12 02:56:48             🧑  作者: Mango

Ruby on Rails CRUD

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并将以下行插入标记之前。

<%= 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%>替换为以下代码:

<% if flash[:notice] %>
<%= flash[:notice] %>
<% end %> <%= yield %>

步骤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的文件夹。在此文件夹中,创建一个名为products的文件夹。现在,最后创建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

 
 
 
 

STOCK LIST

<%= link_to 'Add Product', new_product_path %>

<% @products.each do |product| %>
<% end %>
Name Price Description Actions
<%= product.name %> <%= product.price %> <%= truncate(product.short_description, :length => 75) %> <%= link_to 'Show', product_path(product) %> <%= link_to 'Edit', edit_product_path(product) %> <%= link_to 'Delete', product_path(product), method: :delete %>

new.html.erb

<%= form_for @product, url: {action: :create} do |f| %>

Add a Product

<%= "

#{@product.errors.full_messages.first}
".html_safe if @product.errors.any? %>
<%= f.text_field :name %>
<%= f.text_field :price %>
<%= f.text_field :short_description %>

<%= link_to 'Back', { controller: 'products', action: 'index'} %> <%= f.submit 'Create Product' %>
<% end %>

edit.html.erb

show.html.erb

Add a Product

<%= @product.name %>
<%= @product.price %>
<%= @product.short_description %>
<%= link_to 'Back', { controller: 'products', action: 'index'} %>

步骤19从命令行启动服务器。

rails s

步骤20在本地主机上运行该应用程序。

localhost:3000/products

将出现以下页面。在这里,我们已经在表中插入了一些数据。

插入资料

要插入数据,请单击以上快照中所示的“添加产品”。如下所示填写详细信息。

读取资料

要读取数据,请单击操作显示。在这里,我们将单击“跳伞表演”动作。

更新资料

要更新数据,请单击“编辑操作”。在这里,我们将编辑从男式正装衬衫到女式正装衬衫的衬衫描述。


删除资料

要删除数据,请单击“删除”操作。在这里,我们将从上表中删除产品牛仔裤。

下载