我们将看到一个示例, 用于查看应用程序中的数据。
步骤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文件。
<h3>STOCK LIST</h3>
<div>
<%= link_to 'Add Product', new_product_path %>
</div>
<br>
<table class="table table-bordered table-striped">
<tr>
<th>Name</th>
<th>Price</th>
<th>Description</th>
</tr>
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.price %></td>
<td><%= truncate(product.short_description, :length => 75) %></td>
<td><%= link_to 'Delete', product_path(product), method: :delete %></td>
</tr>
<% end %>
</table>
步骤8转到app / views / products / new.html.erb文件。
<%= form_for @product, url: {action: :create} do |f| %>
<h3>Add a Product</h3>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :price %>
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :short_description %>
<%= f.text_field :short_description %>
</div>
</p>
</div>
<div class="actions">
<%= link_to 'Back', { controller: 'products', action: 'index'} %>
<%= f.submit 'Create Product' %>
</div>
<% end %>
</div>
步骤9启动服务器。
rails s
步骤10在本地主机上运行它。
http://localhost:3000/products
下载
下载此示例