Reputation: 195
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
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
Reputation: 15515
You could just order the result by name:
@posts = @customer.posts.where("name ? = OR name ? =", "Google", "Yahoo").order(name: :asc)
Upvotes: 0
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