尝试解决 rails 控制器活动记录中的“.includes”问题

Trying to solve for a '.includes' issue in rails controller active record

我是一个非常菜鸟的 ROR 编码器,但我试图解决这个问题却没有成功。我有一个正在访问两个模型的应用程序:

-约会(属于某个地点) -地点(有很多约会)

在我的约会索引页面上,我使用 gmap4rails gem 显示了带有图钉的位置地图。一切正常,但我不知道如何将@appointments 限制在附近的那些位置...

def index
  @appointments = Appointment.where(active: "TRUE").order("created_at DESC")
  @hash = Gmaps4rails.build_markers(@appointments) do |appointment, marker|
    marker.lat appointment.location.latitude
    marker.lng appointment.location.longitude
  end
end

这让我得到了所有有效的约会。它在我的位置索引上工作:

def index
  if params[:search].present?
    @locations = Location.near(params[:search], 50)
  else
    @locations = Location.near([session[:latitude], session[:longitude]], 50)
  end
    @hash = Gmaps4rails.build_markers(@locations) do |location, marker|
      marker.lat location.latitude
      marker.lng location.longitude
  end
end

我已经尝试了该查询的每个变体以包含 Appointment.location.near...

我在这里错过了什么???

以下是模型:

class Appointment < ActiveRecord::Base
    belongs_to :user
    belongs_to :profile
    belongs_to :length
    belongs_to :location

    has_many :confirmations

    validates_presence_of :title, :comments
end

地点...

class Location < ActiveRecord::Base

    geocoded_by :address

    def address
      [address_1, city, state, zip].compact.join(', ')
    end

    after_validation :geocode, :if => :address_1_changed?

    has_many :profile_locations
    has_many :profiles, through: :profile_locations

    has_many :appointments
end

试试这个:

# Appointments controller
def index
  nearby_locations = Location.near([session[:latitude], session[:longitude]], 50)
  @appointments = Appointment.where(location: nearby_locations).where(active: true).order(created_at: :desc)
  ...
end

请注意,您可以传递 objects/ids 的数组(如上面的 nearby_locations)来取回对象集合(上面的@appointments)。您还可以使用多个 wheres 链接查询。

经过无数次不同的错误,我终于弄明白了...

def index
    location_ids = Location.near([session[:latitude], session[:longitude]], 50, order: '').pluck(:id)
    @appointments = Appointment.includes(:location).where(location_id: location_ids).where(active: "TRUE").order("created_at DESC")

    @hash = Gmaps4rails.build_markers(@appointments) do |appointment, marker|
      marker.lat appointment.location.latitude
      marker.lng appointment.location.longitude
    end
end

感谢您的指导,但还需要稍微调整一下。