2015-09-27 94 views
0

我有这个疑问:Rails视图问题与ActiveRecord的关系

<% @answer = Answer.where(:question_id => @question.id, :correct => 1) %> 

结果是:

#<ActiveRecord::Relation [#<Answer id: 535, body: "d", notice: "", correct: true, question_id: 50, created_at: "2015-09-26 10:09:10", updated_at: "2015-09-26 10:09:10">]> 

当我想这样做:

<%= @answer.body %> 

我得到这个错误:

undefined method `body' for <Answer::ActiveRecord_Relation:0x0000000e99b7c8> 

怎么回事?

回答

1

A where查询返回一个对象集合ActiveRecord_Relation

为了使该代码正常工作,您必须附加.last.first.find(id)以返回单个对象。

<% @answer = Answer.where(:question_id => @question.id, :correct => 1).last %> 
+0

谢谢。我试着用.first。 这种情况下的区别是什么:第一个dosn't工作? – Felix

+0

如果你没有收到'@ answer.body'的响应,这应该没有什么区别,这可能意味着':body'属性是空的。试试'rails console'中的'where'查询,这样你就可以看到完整的响应。 – miler350

+0

神秘... ...第一次没有工作... – Felix

2

undefined method `body' for Answer::ActiveRecord_Relation:0x0000000e99b7c8

正如你看到@answer返回ActiveRecord::Relation这是记录/对象的集合,这样你就不能简单地使用@answer.body

解决方案:

可以遍历@answer

<% @answer.each do |answer| %> 
    <%= answer.body %> 
<% end %> 
+1

或者,如果您想要一条记录,则可以使用'find_by'而不是'where'。 – ufuoma

0

where返回ActiveRecord::Relation(看起来像一个数组,但没有),这是模型对象的集合,所以@答案是一个集合,你不能用它直接调用body属性。

你可以这样做:

<% @answer = Answer.where(:question_id => @question.id, :correct => 1).first %> 

或:

<% @answer = Answer.find_by_question_id_and_correct(@question.id, 1) %> 

如果记录存在,它会返回一个对象。