如何在 Rails 中的 ActiveRecord::Result 中分割单个列(带有值)?
How to slice individual columns (with values) in an ActiveRecord::Result 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 列的值:topic
和 thread_id
.
我想将 query_results
分成 2 个数组 - 1 个包含列 topic
的所有记录(来自 query_results
)的值单独和第二个包含列 thread_id
单独的所有记录的值。
我怎样才能做到这一点?
我想你可以尝试下面的代码来满足你的要求:-
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]
试试这个可以帮助你!
这里要用到pluck
是的。 According to Rails guides,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]
我有一个 Rails 查询,如下所示:
query_results =
User.
joins("INNER JOIN posts ON posts.user_id = users.user_id").
select("posts.topic, posts.thread_id")
query_results
包含 2 列的值:topic
和 thread_id
.
我想将 query_results
分成 2 个数组 - 1 个包含列 topic
的所有记录(来自 query_results
)的值单独和第二个包含列 thread_id
单独的所有记录的值。
我怎样才能做到这一点?
我想你可以尝试下面的代码来满足你的要求:-
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]
试试这个可以帮助你!
这里要用到pluck
是的。 According to Rails guides,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]