Ruby on rails 如何从Rails视图访问数据库信息?
当我尝试查看index.html.erb文件时,出现以下错误:Ruby on rails 如何从Rails视图访问数据库信息?,ruby-on-rails,Ruby On Rails,当我尝试查看index.html.erb文件时,出现以下错误: NoMethodError in Products#index undefined method `name' for #<Product:0x4a77de8> 产品中的命名错误#索引 未定义的方法“名称”# 这是我的密码 控制器: class ProductsController < ApplicationController . . . def index @products =
NoMethodError in Products#index
undefined method `name' for #<Product:0x4a77de8>
产品中的命名错误#索引
未定义的方法“名称”#
这是我的密码
控制器:
class ProductsController < ApplicationController
.
.
.
def index
@products = Product.all
end
end
class ProductsController
视图:
产品清单
我以为控制器会将我输入的所有条目收集到数据库中的“Product”表中,并将它们放入@products变量中。之后,我认为视图应该遍历@products中的项目,调用每个产品的名称、描述、价格值并输出一个表
我哪里出了问题
非常感谢您的帮助。在
产品
表中是否有名称栏?你忘记迁移数据库了吗?是的,我已经迁移了。我也可以进入控制台键入Product.name,它就可以工作了。你能试试Product.first.name
或Product.last.name
吗?当我尝试Product.first.name
时,它会说未定义的方法“first”
你能发布你的产品
型号吗
<h1>List of products</h1>
<table>
<% @products.each do |product| %>
<tr>
<td>
<%= product.name %>
</td>
<td>
<%= product.description %>
</td>
<td>
<%= product.price %>
</td>
</tr>
<% end %>
</table>