我已经创建了我的搜索,并且我试图在没有提供某些参数的情况下添加条件。
这就是它的样子:
控制器:
@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
除非我不提供参数[:geolocation]
,否则一切都很有效如果用户没有输入城市名称,我希望能够返回用户附近的可用性。
我的网址如下:localhost:3000/s?activity=1
从那里,在Venues模型中,我想返回靠近用户位置的场地。
我一直在关注Geocoder并使用request.location
,但这并不适用于模型级别。有什么建议吗?
我还考虑过动态地将IP地址添加到网址中,但如果我这样做,如果共享了网址,则会返回错误的结果。
答案 0 :(得分:1)
您需要从控制器传递到模型的位置。模型无法访问request
,因为它们的设计目的不仅仅是请求周期。
您应该将其作为另一个参数传递给search
方法。