我有两个型号,Location
和 Basic
,我使用的是 pg_search和 geocoder gem,如何使用 geocoder near
方法将范围添加到我的 pg_search_scope
或者是否有其他方法可以这样做?
Location
模型有纬度和经度列。
在我的 Controller 中我可以这样做:
# 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)
这可能吗?
谢谢
++++++++++++++++
所以在我的 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
列。
这是我的位置
模型
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
所以我正在尝试链接这些方法。理想情况下,应用程序会首先搜索附近的所有结果,然后搜索附近结果中匹配的字词,然后仅显示适用的字词。
最佳答案
听起来您想要的是 Location
靠近params[:loc]
的小号并与 Basic
相关联与术语 params[:q]
匹配的 s .如果这个解释是错误的,那么其他所有内容都将是错误的。
要完全在数据库中执行此操作,您需要加入 locations
使用 near
添加的条件的表范围与 basics
和 services
使用 pg_search_scope
添加的条件的表格.不幸的是,我还没有找到任何方法来使用 pg_search_scope
与其他表的任意连接,所以我不知道一个简单的基于查询的解决方案。但是如果你的 @business
和 @term
结果比较少,你可以在ruby中加入。在你的 Controller 代码之后:
@matching_businesses = @business & @term.map(&:location)
还有其他方法可以做到这一点,但我们的想法是找到独特的一组 Location
在你的 @business
之间结果以及与 Basic
相关的结果在你的@term
结果。这是另一种可能读起来更清楚的方式:
@matching_businesses = @business.select do |business|
@term.any? { |basic| business.basics.include?(basic) }
end
如果这还不够高效,您可能需要编写自己的查询或通读 pg_search_scope
实现以弄清楚如何使其支持任意连接。
关于ruby-on-rails - rails : How to add scope to pg_search with location search?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945972/