如何在 ActiveRecord::Results in Rails 中对单个列(带值)进行切片?



我有一个Rails查询,如下所示:

query_results = 
User.
joins("INNER JOIN posts ON posts.user_id = users.user_id").
select("posts.topic, posts.thread_id")

query_results包含 2 列的值:topicthread_id

我想将query_results拆分为2 个数组- 1 个包含来自所有记录(来自query_results(的值,仅用于第topic列,第二个包含来自第thread_id列的所有记录的值。

我怎样才能做到这一点?

试试这个可以帮助你!

在这里,我们将使用弹拨。

是的。根据Rails指南,pluck直接将数据库结果转换为数组,而无需构造ActiveRecord对象。这意味着大型查询或经常运行的查询的性能更好。

topic_arr = []
thread_id = []
query_results = User.joins("INNER JOIN posts ON posts.user_id = users.user_id").pluck("posts.topic, posts.thread_id")
query_results.each do |i|
topic_arr.push(i.first)
thread_id.push(i.last)
end
puts query_results #=>[["topic1", 1], ["topic2", 2], ["topic3", 3]]
puts topic_arr #=>["topic1","topic2","topic3"]
puts thread_id #=>[1,2,3]

我认为您可以尝试以下代码以满足您的要求:-

query_results = 
User.
joins("INNER JOIN posts ON posts.user_id = users.user_id").
pluck("posts.topic, posts.thread_id").to_h
topic_arr = query_results.keys
thread_id_arr = query_results.values

上面的查询将为您提供如下结果:-

query_results = {"topic 1"=>1, "topic 2" => 2} 
topic_arr = query_results.keys
topic_arr = ["topic 1", "topic 2"] 
thread_id_arr = query_results.values
thread_id_arr = [1, 2] 

最新更新