简体   繁体   中英

Filtering with geokit rails - dosent show any data

I am building an API for a webbapp using Ruby On Rails, i am using Jbuilder for API/JSON and Geokit.

I have this models:

Campaign

class Campaign < ActiveRecord::Base
    belongs_to :company
    belongs_to :venue
    belongs_to :category
    has_and_belongs_to_many :venues
    has_many :cities, through: :venues
    has_many :uses
end

Company

class Company < ActiveRecord::Base
  has_many :venues
  has_many :campaigns
  validates :name, presence: true
end

Venue

class Venue < ActiveRecord::Base

    acts_as_mappable :default_units => :kms,
                     :lat_column_name => :lat,
                     :lng_column_name => :lng

    belongs_to :company
    belongs_to :city
    has_and_belongs_to_many :campaigns

end

I am trying to list all campaigns by given latitude and longitude coordinates, like this:

class API::CampaignsController < ApplicationController
    respond_to :json

    def index
        @campaigns = filter
        respond_with @campaigns
    end
    def filter
        if params[:city_id]
            Campaign.includes(:venues, :cities).where('cities.id' => params[:city_id])
        elsif params[:lat] && params[:lng]
            lat = params[:lat].to_f
            lng = params[:lng].to_f
            Campaign.includes(:venues, :cities).within(10, :origin => [lat, lng])
        end
    end

end

But all I get is a empty hash:

{
campaigns: [ ]
}

Any ides on what I am doing wrong and how I can fix this?

As per the server log, GET "/api/campaigns?lat=55.563466?lng=12.973509" , you are not passing params[:city_id] so your BOTH conditions in filter method will fail and no query would be executed. Hence, empty campaigns .

acts_as_mappable is on Venue model so within is available only for that model. I think you want filter method as below:

  def filter
    if params[:city_id]
      Campaign.includes(:venues, :cities).where('cities.id' => params[:city_id])
    elsif params[:lat] && params[:lng]
      lat = params[:lat].to_f
      lng = params[:lng].to_f
      Venue.within(10, :origin => [lat, lng]).includes(:campaigns, :city).each do |venue|
        campaigns << venue.campaigns  
      end
      campaigns
    end
  end

Also, the url should be /api/campaigns?lat=55.563466&lng=12.973509 .

NOTICE:

Pass lng as a separate query param with & prefix as &lng and not as ?lng

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