Maximus S
Maximus S

Reputation: 11095

A confusion with an array object

I have the following in my view. And I'm trying to figure out why this is happneing:

<% unless @question.answers.empty? %>
  <% @question.answers.each do |answer| %>
    <%= render :partial => '/answers/answer', :locals => { :question => @question, :answer => answer } %>
  <% end %>
<% end %>

problem: @question.answers.empty? returns false when it should be true. It has some null answer object, and @question.answers.length returns 1 instead of 0

Example: [#<Answer id: nil, body: nil, user_id: nil, created_at: nil, updated_at: nil, question_id: 18>]

However, what's more confusing is, when I do it in console, @question.answers.empty? returns true and the length is 0 as it should be. Why is this happening?

1.9.3-p327 :001 > question = Question.find(18)
  Question Load (12.2ms)  SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT 1  [["id", 18]]
 => #<Question id: 18, body: "sddd", user_id: 7, created_at: "2013-01-25 01:47:06", updated_at: "2013-01-25 01:47:06"> 
1.9.3-p327 :002 > question.answers.length
  Answer Load (0.7ms)  SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = 18
 => 0 
1.9.3-p327 :003 > question.answers
 => [] 

Additionally, the particular question's length shows 0 on the index page and 1 on the show page.

Upvotes: 0

Views: 29

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

You probably have something in your controller along the lines of this:

@answer = @question.answers.build

This is creating an object for a new answer and adding it to the @question.answers object. You might want to try .new instead of .build, that way it doesn't get included locally in @question.answers. See Build vs new in Rails 3

Upvotes: 2

Related Questions