user2931706
user2931706

Reputation: 195

Rails how to split into array ActiveRecord AssociationRelation?

Let's say I've got query which fetches 2 types of posts in random order:

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

This returns me ActiveRecord_AssociationRelation object with given posts names And I want to output them in this format:

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

how can i select specific post inside array?

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

Upvotes: 2

Views: 2718

Answers (3)

Ian Kenney
Ian Kenney

Reputation: 6426

Not clear what you are asking but if you want to order the results so that google is before yahoo you could try something like:

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

if you want to convert to an array you could use pluck for example

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

Alternativley - (guessing as your question is not so clear)

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

(you can then re-factor into a helper)

Upvotes: 0

zwippie
zwippie

Reputation: 15515

You could just order the result by name:

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

Upvotes: 0

JMacLeod
JMacLeod

Reputation: 76

It's not quite clear from the question, but you code use the group_by to split the returned posts by name. For example:

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

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

Does that answer the question?

Upvotes: 1

Related Questions