简体   繁体   English

Ruby-访问查询响应的正确方法

[英]Ruby - proper way to access a query response

What is the proper way to access objects inside of an Active Record query response? 在Active Record查询响应中访问对象的正确方法是什么? 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. 我特别想访问question键的值,但是我希望稍后在代码中能够使用其他值。

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. 我不知道如何访问与question键关联的值。 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. 因此,我将查询重新格式化为poll_data = Poll.where(user_id: 1, active: true).pluckpoll_data[0][2] ,但是我知道这是垃圾代码。

ActiveRecord::Relation is a rails class that represents zero, one or more rows from your datastore. ActiveRecord::Relation是一个Rails类,代表数据存储中的零,一或多个行。 The simple information you need to know for use it is probably that this class includes the Enumerable module. 使用时需要了解的简单信息可能是此类包含Enumerable模块。

So, you could call each , first , last , select methods and these are just examples. 因此,您可以调用eachfirstlastselect方法,这些仅是示例。 http://ruby-doc.org/core-2.3.1/Enumerable.html http://ruby-doc.org/core-2.3.1/Enumerable.html

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

Where returns ActiveRecord::Relation you can access the first item simply by doing 在返回ActiveRecord :: Relation的地方,只需执行以下操作即可访问第一项

poll_data.first.question , you can loop through the resultset if you want to perform an operation on each Poll, like this poll_data.first.question ,如果要对每个轮询执行操作,则可以遍历结果集,如下所示

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

There is also a .first , .second , .third and a .fifth for easy retrieval 还有一个.first.second.third.fifth ,以方便检索

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM