Frage

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?

War es hilfreich?

Lösung

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

this is one of many ways.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top