Rails:如何使用位置搜索向pg_search添加范围?

时间:2013-11-13 05:25:28

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 scope

我有两个模型,LocationBasic,我正在使用pg_searchgeocoder gem,如何将范围添加到我的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)这可能吗?

由于

++++++++++++++++

所以在我的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

所以在我的模型中,我有与基本链接的服务。所以当我搜索名称或服务结果弹出时。但我尝试仅在用户输入的某个位置附近显示结果,这就是为什么我的location_id表格中有Basic列。

这是我的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

所以我试图将方法链接起来。理想情况下,应用程序会首先搜索所有附近的结果,然后搜索附近结果中匹配的术语,然后仅显示适用的结果。

1 个答案:

答案 0 :(得分:0)

听起来你想要的是Location附近params[:loc]并与Basic匹配的params[:q]匹配术语locations。如果这种解释是错误的,那么其余的都是错误的。

要在数据库中完全执行此操作,您需要使用near范围添加的条件与basicsservices表一起使用pg_search_scope表加入pg_search_scope表由@business添加的条件。不幸的是,我没有找到任何方法将@term与其他表的任意连接一起使用,所以我不知道一个简单的基于查询的解决方案。但是,如果您的@matching_businesses = @business & @term.map(&:location) Location结果相对较小,则可以在ruby中进行加入。在您的控制器代码之后:

@business

还有其他方法可以做到这一点,但我们的想法是在Basic结果中的@term结果与您@matching_businesses = @business.select do |business| @term.any? { |basic| business.basics.include?(basic) } end 中与pg_search_scope相关的结果中找到唯一的{{1}}组合{{1}}结果。这是另一种可能更清楚地阅读的方式:

{{1}}

如果性能不够,您可能需要编写自己的查询或阅读{{1}}实现,以弄清楚如何使其支持任意连接。