【问题标题】:rails "undefined method" error inside loop which is not evaluated未评估的循环内出现rails“未定义方法”错误
【发布时间】:2012-01-23 13:42:57
【问题描述】:

此代码正常工作(使用 HAML):

#comments
  - @blog.comments.each do |comment|
    .comment
      .username
        - if !eval("comment.user").nil?
          #{comment.user.email}
      .content
        #{comment.content}

但是,如果我删除“eval”行,即

#comments
  - @blog.comments.each do |comment|
    .comment
      .username
        #{comment.user.email}
      .content
        #{comment.content}

我收到一个错误:

undefined method `email' for nil:NilClass

即使数据库中没有 cmets(因此不应评估循环内容)。怎么回事?

【问题讨论】:

  • - if !eval("comment.user").nil? 这很难看,就用- if comment.user
  • @MikhailNikalyukin thx,我一直在寻找更简洁的语法。我以为我以前尝试过,但现在可以了:)

标签: ruby-on-rails ruby haml


【解决方案1】:

尝试以下方法:

#comments
  - @blog.comments.each do |comment|
    .comment
      .username
        - if comment.user
          = comment.user.email
      .content
        = comment.content

我认为问题在于您强制 ruby​​ 使用 #{comment.user.email} 评估 comment.user.email。

在控制台中试试这个:

def fail(param)
  if param
    puts "hello #{1/0}"
  end
end

fail(nil)

会因为被0除而失败,但是param为nil。

【讨论】:

  • OP 询问为什么他会收到 nil.email 错误,而 @blog.cmets 应该是空的,因为 cmets 表在他的数据库中是空的(或者他说 ;))
  • 谢谢,但我相信我在 ERB 模板中也遇到过这个问题(不使用 ${} 语法)
【解决方案2】:

啊,问题解决了!

问题是在发布的代码上方,我有一行:

= form_for @blog.comments.build, :remote => true do |f|

当我将该表单移到循环下方时,错误消失了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多