2015-09-04 36 views
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地址添加到网址,但如果我这样做了,如果网址被共享,它将返回不正确的结果。

回答

1

您需要将位置从控制器传递到模型。模型无法访问request,因为它们被设计为不仅仅在请求周期内被访问。

您应该将它作为另一个参数传递给您的search方法。