📜  Ruby on Rails从数据库查看记录

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

数据库中的Rails视图记录

我们将看到一个示例,用于查看应用程序中的数据。

步骤1创建一个新的Rails应用程序。

rails new viewrecord

步骤2更改目录以保存。

cd viewrecord

步骤3从控制台创建控制器。

rails g controller products index show new create destroy

步骤4从控制台创建模型。

rails g model product name:string price:decimal short_description:text full_description:text

步骤5转到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 

  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 
   
 def product_params 
    params.require(:product).permit(:name, :price, :old_price, :short_description, :full_description) 
  end 
   end 

步骤6运行以下命令:

bundle install

步骤7转到app / views / products / index.html.erb文件。

STOCK LIST

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

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

步骤8转到app / views / products / new.html.erb文件。

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

Add a Product

<%= f.label :name %> <%= f.text_field :name %>
<%= f.label :price %> <%= f.text_field :price %>
<%= f.label :short_description %> <%= f.text_field :short_description %>

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

步骤9启动服务器。

rails s

步骤10在localhost上运行它。

http://localhost:3000/products

下载