【发布时间】:2012-04-23 09:07:31
【问题描述】:
这是我第一次问问题,所以请放轻松:-p
我正在按照http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials(第 3.4.5 节渲染集合)上的示例使用部分渲染集合。代码看起来很简单,但显然我遗漏了一些东西。
models/expert.rb 包含以下行:
attr_accessible :name
experts_controller.rb 在 index 方法中包含以下行:
@experts = Expert.all
views/experts/index.html.erb 包含以下行:
<%= render :partial => "expert", :collection => @experts %>
views/experts/_expert.html.erb 包含:
<%= expert.name %>
在我的浏览器中查看索引页面时,我收到以下错误:
NoMethodError in Experts#index
undefined method `name' for nil:NilClass
我已经为此工作了一个小时,完全被难住了:-/我错过了什么小东西?
---澄清---
在 index.html.erb 中运行“”会产生以下输出:
- !ruby/object:Expert
attributes:
id: 1
name: Bob Smith
slug: bob-smith
created_at: '2012-03-11 18:37:11.791118'
updated_at: '2012-03-11 18:55:58.179629'
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
- !ruby/object:Expert
attributes:
id: 2
name: Steve Kamp
slug: steve-kamp
created_at: !!null
updated_at: !!null
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
【问题讨论】:
-
您的 Expert 模型是否真的有
name字段?attr_accessible允许通过批量分配来分配它,但您必须在架构中创建字段(通常使用迁移)才能使其存在。 -
@Jeremy Roman:nil 类的未定义方法意味着他在 Nil 上调用了#name。如果
@expert不是 nil 但没有 name 属性,他会得到NoMethodError -
欢迎来到 SO,BTW 的第一个问题很好。
-
哦,我错过了它在
nil。我的脑海里又看到了Expert。 (但在这两种情况下都是NoMethodError。) -
@DannyDover:好的,您的错误屏幕应该会显示错误发生的行号,您可以粘贴该行周围的区域吗?或者,更好的是,粘贴到发生错误的整个文件中。
标签: ruby-on-rails ruby-on-rails-3 collections partials