[英]rails: query has_many for a list of objects
I have a model City
: 我有一个示范
City
:
class City
belongs_to :country
end
And a model Street: 和示范街:
//street has an attribute `Type` which can be 1, 2 or 3
class Street
belongs_to City
end
I want all cities in Croatia including streets that are of type 2 我想要克罗地亚的所有城市,包括类型2的街道
So something like this: 所以像这样:
cities = City.find_by_country("Croatie").include_streets_where(type: 2)
so I get something like this: 所以我得到这样的东西:
[
{
name: "Zagreb",
country: "Croatia",
streets: [{name: "street1", type: 2},{name: "street2", type: 2}]
},
{
name: "Split",
country: "Croatia",
streets: [{name: "street3", type: 2},{name: "street4", type: 2}]
}
]
My solution is to first get the cities by country name and loop through each city to query it's streets. 我的解决方案是先按国家/地区名称获取城市,然后遍历每个城市以查询其街道。 But I'm guessing there is a better way.
但是我猜测还有更好的方法。
I'm assuming your City has_many :streets
, and your Country class has an attribute name
. 我假设您的城市
has_many :streets
,并且您的Country类具有一个属性name
。
A 2-layered loop is not as efficient as an INNER JOIN, which you can assemble with this: (You can look at the SQL it generates by appending .to_sql
to the end of it.) 2层循环不如INNER JOIN高效,您可以使用以下方式进行组合:(您可以通过在其末尾附加
.to_sql
来查看它生成的SQL。)
cities = City.where(country: Country.find_by_name("Croatie"))
.joins(:streets).where(streets: { type: 2 })
This will return a list of city
objects matching your criteria. 这将返回符合您条件的
city
对象的列表。 Now to get it to the format you specified, you have to do some formatting on the Ruby side since the default returned is not an Array type. 现在要将其恢复为您指定的格式,您必须在Ruby端进行一些格式化,因为返回的默认值不是Array类型。 This is assuming you want an array of hashes.
假设您要使用散列数组。
formatted_list = cities.map do |city|
{ name: city.name,
country: city.country.name,
streets: list_of_streets_with_type(city.streets) }
end
def list_of_streets_with_type(streets)
streets.map do |street|
{ name: street.name,
type: street.type }
end
end
In the end, formatted_list
would be returning what you wanted. 最后,
formatted_list
将返回您想要的内容。 (Disclaimer: I have not checked syntax, but the general idea is there. Give it a try, it should work) (免责声明:我没有检查语法,但是这里有基本的想法。尝试一下,它应该可以工作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.