简体   繁体   中英

Filter Active Record On Another Active Record

I am still pretty new to rails and trying to figure this out.

I have a couple of models:

appointments = belongs_to vendors vendors has_many locations through vendor_locations

I am filtering some map markers based on locations in the area:

    if params[:search].present?
      location_ids = Location.near(params[:search], 50, order: '').pluck(:id)
      @vendor_locations = VendorLocation.includes(:location).where(location_id: location_ids)
    else
      location_ids = Location.near([session[:latitude], session[:longitude]], 50, order: '').pluck(:id)
      @vendor_locations = VendorLocation.includes(:location).where(location_id: location_ids)
    end

I am trying to filter the active APPOINTMENTS for those that are associated with the vendors in the search area.

I was trying to set the active records with includes:

  def index
if params[:service].blank?
  @appointments = Appointment.includes(:vendor).where(vendors: {id: @vendor_locations.vendor_id})

But thats obviously not working. Any suggestions on how I can filter based on the @vendor_locations?

Pluck vendor_id from vendor_locations to filter appointments:

@vendor_locations = VendorLocation.where(location_id: location_ids)
@appointments = Appointment.
                  includes(:vendor).
                  where vendor_id: @vendor_locations.select(:vendor_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM