class State < ActiveRecord::Base has_many :cities end class City < ActiveRecord::Base belongs_to :state has_many :companies end class Company < ActiveRecord::Base belongs_to :city end
I am trying to list all states and their respective cities containing at least one registered company. My first attempt was the following query:
states = State.joins(:cities => :companies).includes(:cities)
What works, but I get duplicates if the state has more than one city with companies in it. Then I changed the request to:
states = State.joins(:cities => :companies).includes(:cities).select("distinct(states.id)")
This query almost works. I have access to cities (state [0] .cities) and there are no duplicates, but if I try to access the attribute from the State object, I get the following error:
ruby-1.9.2-p290 :056 >states[0].name ActiveModel::MissingAttributeError: missing attribute: name
How can i solve this?
Thank you in advance
source share