sql - Rails joins through association -


in ruby on rails, want find employers in city. lets models set way:

city has_many :suburbs has_many :households, :through => suburbs has_many :people, :through => suburbs  suburb has_many :households has_many people, :through => households belongs_to :city   household has_many :people belongs_to :suburb  people belongs_to :household belongs_to :employer   employer has_many :people 

i feel want sort of employer joins some_city.people don't know how this. if people belonged directly cities, join employer people city_id something, want find same data without direct join , little lost.

thank you.

you can join jvans has illustrated. or can setup relationships following:

class employer < activerecord::base   has_many :people   has_many :households, through: :people   has_many :suburbs, through: :households   has_many :cities, through: :suburbs end  class person < activerecord::base   belongs_to :household   belongs_to :employer end   class household < activerecord::base   belongs_to :suburb   has_many :people end  class suburb < activerecord::base   belongs_to :city   has_many :households   has_many :people, through: :households end  class city < activerecord::base   has_many :suburbs   has_many :households, through: :suburbs   has_many :people, through: :households   has_many :employers, through: :people end 

then can join city employer, , vice-versa, directly.

for example:

employer.joins(:cities).where("cities.name = ?", "houston").first  select "employers".* "employers"  inner join "people" on "people"."employer_id" = "employers"."id"  inner join "households" on "households"."id" = "people"."household_id"  inner join "suburbs" on "suburbs"."id" = "households"."suburb_id"  inner join "cities" on "cities"."id" = "suburbs"."city_id" (cities.name = 'houston')  limit 1 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -