在我看来,我有以下几点。我试图弄清楚为什么会这样:
<% unless @question.answers.empty? %>
<% @question.answers.each do |answer| %>
<%= render :partial => '/answers/answer', :locals => { :question => @question, :answer => answer } %>
<% end %>
<% end %>
问题:在应该@question.answers.empty?
返回的时候返回。它有一些空对象,并返回而不是false
true
answer
@question.answers.length
1
0
例子:[#<Answer id: nil, body: nil, user_id: nil, created_at: nil, updated_at: nil, question_id: 18>]
但是,更令人困惑的是,当我在控制台中执行此操作时,@question.answers.empty?返回 true 并且长度应该是 0。为什么会这样?
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
=> []
此外,特定问题的长度在索引页面上显示为 0,在显示页面上显示为 1。