Rails的3.1独特的发现和缺少的属性 [英] Rails 3.1 distinct find 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'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)")
这个查询几乎工程。我有机会到城市(州[0] .cities),而且没有重复,但如果我尝试从国家访问对象的属性,我收到以下错误:
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?
在此先感谢
推荐答案
SELECT语句覆盖默认的( SELECT * FROM ...
变成 SELECT DISTINCT(state.id)FROM ...
),这样的结果并不包括你的状态表(其中属性是从推断)的列。试着改变你的选择的方法如下:
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.*")
这篇关于Rails的3.1独特的发现和缺少的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!