获取模型内的用户坐标

Get user coordinates within model

我已经创建了我的搜索,我正在尝试为未提供某些参数时添加条件。

这是它的样子:

控制器:

@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]

我希望能够 return 在用户未输入城市名称的情况下接近用户的可用性。

我的 url 看起来像这样:localhost:3000/s?activity=1

从那里开始,在场地模型中,我想要 return 靠近用户位置的场地。

我一直在查看 Geocoder 并使用 request.location 但这在模型级别不起作用。有什么建议吗?

我还考虑过将 IP 地址动态添加到 url,但如果我这样做,如果 url 被共享,它会 return 不正确的结果。

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

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