user1436111
user1436111

Reputation: 2141

Best way to join two different model queries in Rails?

I have two different models that I need to join together in a selection query and list on a page. They share all of attributes that I'll need to reference in the view (created_at, updated_at, name, etc), and I want them in order of creation. I'm wondering what the most efficient way to do this is? I was thinking of performing the selection query on each object individually and adding the relevant parts into a common array but that seems inefficient.

For example if my models were Dogs and Cats and I wanted a list of all dogs and cats of age 5, I was thinking something like

@pets = []
dogs = Dogs.where(:age => 5)
cats = Cats.where(:age => 5)
dogs.each do |dog|
  hash = {"id" => dog.id, "name" => dog.name, "created_at" => dog.created_at }
  @pets.push(hash)
end 
cats.each do |cat|
  hash = {"id" => cat.id, "name" => cat.name, "created_at" => cat.created_at }
  @pets.push(hash)
end 

But is that the best way to do it? also, I'm not sure how to sort the finished array in this example according to date created...

Upvotes: 0

Views: 103

Answers (1)

house9
house9

Reputation: 20614

try this

dogs = Dogs.where(:age => 5)
cats = Cats.where(:age => 5)
@pets = (dogs + cats).sort_by { |pet| pet.created_at }

OR if you want your hashes still, use map to create the array of hashes

dogs = Dogs.where(:age => 5)
cats = Cats.where(:age => 5)
@pets = (dogs + cats).sort_by do |pet| 
  pet.created_at 
end.map do |pet| 
  { "id" => dog.id, "name" => pet.name, "created_at" => pet.created_at }
end

Upvotes: 1

Related Questions