Question

this is my first question on StackOverflow :)

I'm building a Rails 4 app, having trouble to figure out a good way to load records from mutilple data models. I could hard code SQL statements like an inner join, but wondering if there's any better way. Searched in existing questions on SO, but didn't find a match.

Here are my models:

class Person < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :person
  belongs_to :city
end

class City < ActiveRecord::Base
  has_many :addresses
end

Question: given a person Id, how should I load its associated addresses with the city information?

Was it helpful?

Solution

Address.includes(:persons,:cities).where(person_id: person.id)

this is one of many ways.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top