Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 铁路";“未定义的方法”;未计算的循环内部错误_Ruby On Rails_Ruby_Haml - Fatal编程技术网

Ruby on rails 铁路";“未定义的方法”;未计算的循环内部错误

Ruby on rails 铁路";“未定义的方法”;未计算的循环内部错误,ruby-on-rails,ruby,haml,Ruby On Rails,Ruby,Haml,此代码正常工作(使用HAML): 但是,如果我删除“eval”行,即 #comments - @blog.comments.each do |comment| .comment .username #{comment.user.email} .content #{comment.content} 我得到一个错误: undefined method `email' for nil:NilClass 即使数据库中没有注释(因此不

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

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

#comments
  - @blog.comments.each do |comment|
    .comment
      .username
        #{comment.user.email}
      .content
        #{comment.content}
我得到一个错误:

undefined method `email' for nil:NilClass
即使数据库中没有注释(因此不应评估循环内容)。发生了什么事?

请尝试以下操作:

#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为零。

啊,问题解决了

问题是,在张贴的代码上方,我有一行:

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

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

-if!eval(“comment.user”).nil?
这很难看,只需使用
-如果comment.user
@MikhailNikalyukin-thx,我正在寻找更清晰的语法。我想我以前试过,但现在可以了:)OP问他为什么会出现nil.email错误,而@blog.comments应该是空的,因为他的DB(或者他说;)thx中的comments表是空的,但我相信我在ERB模板中也遇到过这个问题(没有使用${}语法)
= form_for @blog.comments.build, :remote => true do |f|