简体   繁体   中英

Rails query associated model

I'm forking a repo off another to be a standalone for a client and for whatever reason I'm having a brain freeze.

Looking to set specific queries to only hit this one Region: Southwest and then all locations associated.

So naturally the model structure is:

Region
has_many :locations

Location
belongs_to :region

I'm looking at updating some code to specifically hit the Region Southwest in some helpers and it's far too clunky.

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

I'm really looking at updating the southwest_locations method to hit the Region model through Locations. I thought I could do something:

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

But that's really more of a search not a db query right?

特定地区的位置

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

I'd do this like this, which I think shows the intent far better:

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

I should note that this will perform two queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM