[英]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.