我是非常棒的ROR编码员,但试图找出这个问题没有运气。我有一个访问两个模型的应用程序:
- 约会(属于某个地点) -Locations(有许多约会)
在我的约会索引页面上,我使用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
这只能让我获得所有活跃的约会。它在我的Locations索引上工作:
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
答案 0 :(得分:0)
试试这个:
# 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
请注意,您可以传递一个对象/ ID数组(如上面的nearby_locations)来获取对象集合(上面的@appointments)。您还可以链接多个查询。
答案 1 :(得分:0)
经过多次不同的错误后,我终于明白了......
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
感谢您的指导,但只需要进行一些调整。