嗨,我是新手。我正在尝试从数据库渲染数据并显示。我几乎成功了,但是它没有显示数据,如下图所示。
Companies List
Name Place
**VIEW**(Click of this is working and navigating nothing is displaying)
ADD New Company
这是我的控制器代码:
class CompaniesController < ApplicationController
def index
@companies = Company.all
end
def show
@companies = Company.find(params[:id])
end
def new
@companies = Company.new
end
def create
@companies = Company.new(params[:Company])
if @companies.save
flash[:success] = "Welcome to skillable"
redirect_to root_url
else
render 'new'
end
end
end
这是我的视图代码index.html.erb
<h1>Companies List</h1>
<table>
<tr>
<th>Name</th>
<th>Place</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @companies.each do |companies| %>
<tr>
<td><%= companies.name %></td>
<td><%= companies.place %></td>
<td><%= link_to 'VIEW', companies %></td>
<% end %>
</table>
<br />
<%= link_to 'ADD New Company', new_company_path %>
所以谁能告诉我我的问题是什么。为什么它不显示。请我无法解决我的问题。
首先,在索引页面中,我将编写:
<% @companies.each do |company| %>
<tr>
<td><%= company.name %></td>
<td><%= company.place %></td>
<td><%= link_to 'VIEW', company %></td>
</tr>
<% end %>
这将显示公司列表。接下来,点击“查看”即可将您带到以下/companies/1
位置1
:的ID在哪里company
。这意味着您将在公司控制器的显示操作中按ID查找公司:
def show
@company = Company.find(params[:id])
end
看看我怎么称呼变量- @company
,不是@companies
因为我假设show.html.erb
您已经使用过@company
变量(或者肯定是由脚手架创建的@company
),这也只是一个页面company
,因此更适合以单数形式(而不是公司)公司)。
完成上述所有操作,例如将在显示页面中使用ex:
<%= @company.name %>
PS 1您对new
和create
动作有相同的命名问题,我会这样做:
def new
@company = Company.new
end
这将让我以如下形式使用此变量:
<%= form_for @company do |f| %>
....
<% end %>
和:
def create
@company = Company.new(params[:company])
if @company.save
flash[:success] = "Welcome to skillable"
redirect_to root_url
else
render 'new'
end
end
PS 2
检查数据库中是否有东西-打开rails console
:
your/project/path/ rails c
x.x.x-pxxx :001 > Company.first
Company Load (18.2ms) SELECT "companies".* FROM "companies" LIMIT 1
=> nil
如果结果为nil
,则表示您在db中什么都没有,否则-您内部有记录。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句