0

This code works properly (using HAML):

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

However, if I remove the "eval" line i.e.

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

I get an error:

undefined method `email' for nil:NilClass

Even when there are no comments in the database (hence the loop contents should not be evaluated). What is going on?

2
  • 2
    - if !eval("comment.user").nil? this is ugly, just use - if comment.user Commented Jan 23, 2012 at 13:54
  • @MikhailNikalyukin thx, I was looking for some cleaner syntax. I thought I tried that before, but it works now :) Commented Jan 23, 2012 at 16:45

2 Answers 2

1

Try the following:

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

I think the problem is that you are forcing ruby to evaluate comment.user.email with #{comment.user.email}.

Try this in the console:

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

fail(nil)

It will fail because of a division by 0, but param is nil.

Sign up to request clarification or add additional context in comments.

2 Comments

The OP is asking why he's getting the nil.email bug whereas @blog.comments should be empty, since the comments table is empty in his DB (or so he says ;))
thx, but I believe I've had this issue in ERB templates too (without using ${} syntax)
1

Ah, problem solved!

Issue was that above the posted code, I had the line:

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

When I moved that form below the loop the error disappeared.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.