我认为我有以下内容。我正在试图弄清楚为什么这会让你感到高兴:
<% 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。
答案 0 :(得分:2)
你可能在控制器中有一些东西:
@answer = @question.answers.build
这是为新答案创建一个对象并将其添加到@question.answers
对象。您可能希望尝试使用.new
而不是.build
,这样就不会在@question.answers
中将其包含在本地。见Build vs new in Rails 3