Rails 3.1 distinct find and missing attributes

风流意气都作罢 提交于 2019-12-07 09:16:18

问题


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'm trying to list all states, and their respective cities, that contain at least one company registered. My first try was the following query:

states = State.joins(:cities => :companies).includes(:cities)

Which works, but I end up getting duplicates if a state has more than one city with companies in it. I then changed the query to:

states = State.joins(:cities => :companies).includes(:cities).select("distinct(states.id)")

This query almost works. I have access to the cities (states[0].cities), and there are no duplicates, but if I try to access an 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?

Thanks in advance


回答1:


Your select statement overrides the default (SELECT * FROM ... becomes SELECT distinct(state.id) FROM...) so the results don't include the columns of your state table (where the attributes are inferred from). Try changing your select method to the following:

.select("distinct(states.id), states.*")


来源:https://stackoverflow.com/questions/7419577/rails-3-1-distinct-find-and-missing-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!