Kermit
Kermit

Reputation: 5992

Ruby - proper way to access a query response

What is the proper way to access objects inside of an Active Record query response? I specifically want to access the value of the question key, but I want to be able to use the other values later in my code.

from -e:1:in `<main>'irb(main):008:0> poll_data
=> #<ActiveRecord::Relation [#<Poll id: 1, user_id: 1, question: "(conorao) - Which NFL team do you like the best?", poll_type: "multiple_choice", active: true, created_at: "2017-02-17 21:08:40", updated_at: "2017-02-17 21:08:40">]>
irb(main):009:0> poll_data.class
=> Poll::ActiveRecord_Relation

I could not figure out how to access the value associated with the question key. So I reformatted the query to poll_data = Poll.where(user_id: 1, active: true).pluck and the accessor to poll_data[0][2] , but I know this is garbage code.

Upvotes: 0

Views: 127

Answers (2)

theterminalguy
theterminalguy

Reputation: 1941

Where returns ActiveRecord::Relation you can access the first item simply by doing

poll_data.first.question, you can loop through the resultset if you want to perform an operation on each Poll, like this

poll_data.each do |poll| 
  puts poll.question
end 

There is also a .first, .second, .third and a .fifth for easy retrieval

Upvotes: 0

Ursus
Ursus

Reputation: 30056

ActiveRecord::Relation is a rails class that represents zero, one or more rows from your datastore. The simple information you need to know for use it is probably that this class includes the Enumerable module.

So, you could call each, first, last, select methods and these are just examples. http://ruby-doc.org/core-2.3.1/Enumerable.html

poll_data.each do |item|
  puts item.question
end

Upvotes: 2

Related Questions