0

在我看来,我有以下几点。我试图弄清楚为什么会这样:

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

问题:在应该@question.answers.empty?返回的时候返回。它有一些空对象,并返回而不是falsetrueanswer@question.answers.length10

例子:[#<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。

4

1 回答 1

2

您的控制器中可能有以下内容:

@answer = @question.answers.build

这是为新答案创建一个对象并将其添加到@question.answers对象中。您可能想尝试.new而不是.build,这样它就不会在本地包含在@question.answers. 请参阅Rails 3 中的 Build vs new

于 2013-01-25T02:00:39.763 回答