Rails 3.1 Great Search and Missing Attributes

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

+4
source share
1 answer

Your select statement overrides the default value ( SELECT * FROM ... becomes SELECT distinct(state.id) FROM... ), so the columns of your state table (where the attributes are derived from) are not included in the results. Try changing your selection method to the following:

 .select("distinct(states.id), states.*") 
+2
source

All Articles