0
我創建了我的搜索,並且我試圖爲未提供某些參數時添加條件。獲取模型中的用戶座標
這是什麼樣子:
控制器:
@search = Availability.search(params)
Availability.rb:
# Scopes for search filters
scope :close_to, -> (venues) {where{facility.venue_id.in venues}}
scope :activity, -> (activity) {where{facility.activities.id == activity}}
scope :start_date, -> (datetime) {where{start_time >= datetime}}
scope :end_date, -> (datetime) {where{end_time <= datetime}}
scope :not_booked, -> {where(booking: nil)}
scope :ordered, -> {order{start_time.desc}}
scope :join, -> {joins{facility.activities}}
# Main search function
def self.search params
# Check if date is nil
def self.date_check date
date.to_datetime if date
end
search = {
venues: Venue.close_to(params[:geolocation]),
activity: params[:activity].to_i,
start_date: date_check(params[:start_time]) || DateTime.now,
end_date: date_check(params[:end_time]) || 1.week.from_now
}
result = self.join.not_booked
result = result.close_to(search[:venues])
result = result.activity(search[:activity])
result = result.start_date(search[:start_date])
result = result.end_date(search[:end_date])
result.ordered
end
Venue.rb除非
# Scope venues near geolocation
scope :close_to, -> (coordinates) {near(get_location(coordinates), 20, units: :km, order: '').pluck(:id)}
# If given coordinates, parse them otherwise generate them
def self.get_location coordinates=nil
if coordinates
JSON.parse coordinates
else
location = request.location
[location.latitude, location.longitude]
end
end
一切的偉大工程我不提供params [:geolocation]
我希望能夠返回與用戶接近的可用性,例如,如果用戶沒有輸入城市名稱。
我的網址是這樣的:localhost:3000/s?activity=1
從那裏,在場地模型,我想回到那些靠近用戶所在地場地。
我一直在尋找地理編碼器,並使用request.location
但這不適用於模型級別。有什麼建議麼?
我也考慮動態地將IP地址添加到網址,但如果我這樣做了,如果網址被共享,它將返回不正確的結果。