PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to make a single query to retrieve objects related to a model through a join table in ruby on rails

 October 21, 2022     has-many, has-many-through, mysql, ruby-on-rails, sql     No comments   

Issue

I have models related as follows:

Country 
  has_many :states

State 
  belongs_to :country
  has_many :counties

County 
  belongs_to :State
  has_many :municipalities
  has_many :cities, through: :municipalities

City
  has_many :municipalities
  has_many :counties, through: :municipalities 

Municipality
  belongs_to :county
  belongs_to :city

I'd like to be able to call something like @country.cities and have it return all the cities that belong to a country through its related objects. Any feedback is appreciated, thanks!


Solution

Here you go:

Country 
  has_many :states
  has_many :counties      , through: :states
  has_many :municipalities, through: :counties
  has_many :cities        , through: :municipalities


Answered By - David Aldridge
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing