[英]Rails: How to add scope to pg_search with location search?
我有两个型号, Location
和Basic
,我使用pg_search和地理编码的宝石,我怎么添加范围,我pg_search_scope
与地理编码器 near
方法或是否有其他方法来做到这一点?
Location
模型具有纬度和经度列。
在我的控制器中,我能够做到这一点:
# this allows me to search near the Location model
@business = Location.near(params[:loc], 15)
# this searches through the pg_search_scope
@term = Basic.search(params[:q])
#I'm trying to combine @business and @term
使用Basic
模型我有这个:
pg_search_scope :search, :against => [:first_name, :last_name],
:associated_against => {
:services => [:service, :description]
},
:using => {
:tsearch => {:disctionary => "english" }
}
我想将@business
和@term
(@search)
@term
(@search)
这可能吗?
谢谢
++++++++++++++++
所以在我的Basic
模型中:
class Basic < ActiveRecord::Base
belongs_to :location
has_many :services, as: :servicable
pg_search_scope :search, :against => [:first_name, :last_name],
:associated_against => {
:services => [:service, :description]
},
:using => {
:tsearch => {:disctionary => "english" }
}
end
所以在我的模型中,我有与基本链接的服务。 所以当我搜索名称或服务结果弹出时。 但我试图只在用户输入的某个位置附近显示结果,这就是为什么我在Basic
表中有一个location_id
列。
这是我的Location
模型
class Location < ActiveRecord::Base
has_many :basics
geocoded_by :new_address
after_validation :geocode, :if => :new_address_changed?
def gmaps4rails_address
:new_address
end
def new_address_changed?
attrs = %w(street city state)
attrs.any?{|a| send "#{a}_changed?"}
end
end
所以我试图链接这些方法。 理想情况下,应用程序首先搜索所有附近的结果,然后搜索附近结果中匹配的术语,然后仅显示适用的结果。
听起来你想要的是位于params[:loc]
附近且与Basic
s相关的Location
s与params[:q]
相匹配。 如果这种解释是错误的,那么其余的都是错误的。
要在数据库中完全执行此操作,您需要使用near
范围添加的条件以及使用pg_search_scope
添加的条件的basics
和services
表来连接locations
表。 不幸的是,我没有找到任何方法使用pg_search_scope
与其他表的任意连接,所以我不知道一个简单的基于查询的解决方案。 但是如果你的@business
和@term
结果相对较小,你可以在ruby中进行连接。 在你的控制器代码后:
@matching_businesses = @business & @term.map(&:location)
还有其他的方法来做到这一点,但这个想法是找到独特的Location
那些在您s之间@business
结果以及相关的那些Basic
在你的@term
结果。 这是另一种可能更清楚地阅读的方式:
@matching_businesses = @business.select do |business|
@term.any? { |basic| business.basics.include?(basic) }
end
如果这不够pg_search_scope
,您可能需要编写自己的查询或通过pg_search_scope
实现读取,以弄清楚如何使其支持任意连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.