简体   繁体   English

Rails通过belongs_to关系方法查询

[英]Rails querying by belongs_to relationship method

I have a model Location which many models use to store geographic-type information. 我有一个模型位置,许多模型都使用该模型来存储地理类型的信息。 I am using https://github.com/alexreisner/geocoder to filter results based on location. 我正在使用https://github.com/alexreisner/geocoder来基于位置过滤结果。 My issue is, how do I call the .near method on the belongs_to location. 我的问题是,如何在belongs_to位置上调用.near方法。 Example: 例:

I have a User 我有一个用户

class User < ActiveRecord::Base
  belongs_to :location
end

Location: 位置:

class Location < ActiveRecord::Base
end

I would normally join Location and query from there: 我通常会加入Location并从那里查询:

User.joins(:location).where('locations.country = ""')

The issue is, I can not pass a hash or a string, I need to call a method from Location, something like 问题是,我无法传递哈希或字符串,我需要从Location调用方法,例如

# Instead of calling .near on User, I need to on Location
User.joins(:location).near('Omaha, NE, US', 20)

I am not sure how I can do this, or if it is possible. 我不确定该怎么做,或者是否可行。 Thanks 谢谢

You can query on Location with a join on User , even without a relation defined from Location to User , and get the id of the users : 您可以User上的Location来查询Location ,即使没有从LocationUser定义关系,也可以获取User的ID:

users_id = Location.join('INNER JOIN users ON users.location_id = locations.id').near('Omaha, NE, US', 20).pluck('users.id')
users = User.find(users_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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