Felix
Felix

Reputation: 5619

Rails view Problems with ActiveRecord Relation

I have this Query:

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

Result is:

#<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">]>

When I want to do this:

<%= @answer.body %>

I got this error:

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

Whats going wrong?

Upvotes: 0

Views: 1278

Answers (3)

pangpang
pangpang

Reputation: 8821

where returns an ActiveRecord::Relation(looks like an array, but not), which is a collection of model objects, so @answer is a collection, you can't use it to invoke body attribute directly.

You can do like this:

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

or:

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

It will return a single object if record exists.

Upvotes: 0

miler350
miler350

Reputation: 1421

A where query returns an ActiveRecord_Relation which is a collection of objects.

In order for that code to work, you have to append .last or .first or .find(id) to return a single object.

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

Upvotes: 1

Pavan
Pavan

Reputation: 33542

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

As you see @answer returns a ActiveRecord::Relation which is a collection of records/objects, so you just can't simply use @answer.body.

Solution:

You can iterate over @answer

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

Upvotes: 3

Related Questions