Rails查询关联的模型

时间:2019-01-28 20:35:40

标签: ruby-on-rails

我正在为另一个客户分拆一个回购协议,以使其成为一个独立的客户端,无论出于何种原因,我都陷入了大脑冻结。

希望将特定查询设置为仅击中以下一个地区:西南地区,然后才关联所有位置。

自然,模型结构是:

Region
has_many :locations

Location
belongs_to :region

我正在考虑更新一些代码,以便在某些帮助程序中专门针对西南地区,这太笨拙了。

def southwest_general
 Region.where(name: 'Southwest')
end

def southwest_locations
 Location.where(region_id: 5)
end

def all_locations
 southwest_locations.all.map do |loc|
  pin = { icon: pin_path(loc.region_id) }
  loc.attributes.merge(pin)
 end
end

我真的在考虑更新southwest_locations方法以通过Locations打地区模型。我以为我可以做点什么:

def southwest_locations
 Location.includes(:regions).where('regions.name =?', 'Southwest').references(:regions)
end

但这实际上只是搜索而不是数据库查询吗?

2 个答案:

答案 0 :(得分:1)

特定区域的位置

Location.joins(:region).where(regions: {id: 5}) 

答案 1 :(得分:0)

我会这样做,我认为它的意图要好得多:

Region.find_by(name: 'Southwest').locations

我应该注意,这将执行两个查询。