Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在Rails 4.1中编写以下内容作为一个急切加载的查询?_Ruby On Rails_Ruby_Eager Loading - Fatal编程技术网

Ruby on rails 如何在Rails 4.1中编写以下内容作为一个急切加载的查询?

Ruby on rails 如何在Rails 4.1中编写以下内容作为一个急切加载的查询?,ruby-on-rails,ruby,eager-loading,Ruby On Rails,Ruby,Eager Loading,因此,我在Rails 4.1中使用geocoder gem,并设置了以下模型。代码可以工作,但Bullet gem正在检测这一行places.select{| place |@countries.places.include?place.country}作为N+1查询。有没有一个好的方法通过快速加载来编写它?诀窍是我想返回一组国家,其中只包含Geocoder方法返回的地点 模型设置 编辑:某个_controller.rb的一个更正-应为: places.select { |place| @cou

因此,我在Rails 4.1中使用geocoder gem,并设置了以下模型。代码可以工作,但Bullet gem正在检测这一行places.select{| place |@countries.places.include?place.country}作为N+1查询。有没有一个好的方法通过快速加载来编写它?诀窍是我想返回一组国家,其中只包含Geocoder方法返回的地点

模型设置

编辑:某个_controller.rb的一个更正-应为:

places.select { |place| @countries.include?(place.country) }

正如下面的注释所指出的,Country.all实际上只是一个占位符,以便更容易阅读代码。事实上,@国家实际上是国家的另一个子集,而不是国家。所有国家都有一些财产,比如所有共产主义国家。因此,我想找到某一组坐标附近的国家和具有某些属性的国家(如所有共产主义国家)的交点。

没有尝试过,但应该可以:

@countries = Country.all
places = Place.includes(:country).near(some_latitude_longitude_coordinates, 5500)
places.select { |place| @countries.include?(place.country) }

这将为您找到@countries集合中包含其国家/地区的位置。

要加载您的记录,您需要进行一次查询。我建议如下:

@places = Place.near(some_latitude_longitude_coordinates, 5500).joins(:country).where(country_id: @countries.map(&:id))

@countries.places.include?place.country这是做什么的?嗨,Tamer,这是一个打字错误-我做了上面的编辑,基本上它是所有国家和在某些坐标附近发现的地方的国家之间的一个交集@国家实际上是国家的另一个子集,而不是国家。所有国家都有一些财产,比如所有共产主义国家请在下面列出我的答案。
@countries = Country.all
places = Place.includes(:country).near(some_latitude_longitude_coordinates, 5500)
places.select { |place| @countries.include?(place.country) }
@places = Place.near(some_latitude_longitude_coordinates, 5500).joins(:country).where(country_id: @countries.map(&:id))