【问题标题】:Collection and Partials in Rails 3Rails 3 中的集合和部分
【发布时间】: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


【解决方案1】:

这个例外几乎肯定意味着没有专家,所以@experts 是一个空数组。您是否创建了任何专家记录?

另外,您会知道,要按照您的方式渲染对象集合,还有一个不错的快捷方式:

render @experts

【讨论】:

  • Expert.all 在没有记录时返回[],而不是nil:collection 然后进行迭代,如果它是 nil(而不是尝试调用 name),则会引发错误。
  • 我相信我有两条记录。 &lt;%= debug expert %&gt; 返回:--- !ruby/object:Expert attributes: id: 1 name: Steve Smith... 以及渲染的第二个局部实例的不同属性组
  • 成功了!问题是在 index.html.erb 中调用了另一个不包含集合的部分实例,此 @experts 未为第二个实例定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-30
相关资源
最近更新 更多