Rails如何拆分成数组ActiveRecord AssociationRelation?

时间:2015-02-12 08:38:48

标签: ruby-on-rails ruby arrays

假设我有查询以随机顺序获取两种类型的帖子:

@posts = @customer.posts.where("name ? = OR name ? =", "Google", "Yahoo")

这会返回给定帖子名称的ActiveRecord_AssociationRelation对象 我想以这种格式输出它们:

output = [
    # here just google posts,
    # here just yahoo posts
]

如何在数组中选择特定的帖子?

Google | Yahoo
Test   | Test yahoo
Test   | Test yahoo
Test   | Test yahoo
Test   | Test yahoo
Test   | Test yahoo

3 个答案:

答案 0 :(得分:1)

问题不是很明确,但您使用group_by代码按名称拆分返回的帖子。例如:

@posts = @customer.posts.where("name ? = OR name ? =", "Google", "Yahoo").group_by(&:name)

@posts.each do |name, posts|
  puts name
  puts posts.count
end

这会回答这个问题吗?

答案 1 :(得分:0)

您可以按名称订购结果:

@posts = @customer.posts.where("name ? = OR name ? =", "Google", "Yahoo").order(name: :asc)

答案 2 :(得分:0)

不清楚你在问什么,但如果你想订购结果以便谷歌在雅虎之前你可以尝试类似的东西:

@posts = @customer.posts.where(name: ["google", "yahoo"]).order(:name)

如果你想转换为数组,你可以使用pluck例如

@posts = @customer.posts.where(name: ["google", "yahoo"]).order(:name).pluck([:name,:id])

Alternativley - (猜测你的问题不是那么清楚)

@posts = [
  @customer.posts.where(name:"google").pluck( [:fields, :you, :want]),
  @customer.posts.where(name:"yahoo").pluck( [:fields, :you, :want])
]

(然后你可以重新考虑帮助)