Question: Is it possible to filter (search) results at query level when using grape gem in Rails 4 app?

Question

Is it possible to filter (search) results at query level when using grape gem in Rails 4 app?

Answers 0
Added at 2017-09-07 17:09
Tags
Question

I am using gem grape to build out an api for an app. i am able to get all the endpoints i want working, however it has been difficult to get search functionality working. In my controllers/schools_controller i have the following:

    #controllers/schools_controller 
    def search
        @schools = School.search(params).all
    end

And my model:

#models/school.rb    
    def self.search(params)
      schools = School.where("school_specialty = ? AND school_location = ?", params[:specialty], params[:search_location]).order("RANDOM()")
      schools
    end

I am using gem active_model_serializer And my school_serializer is this:

class SchoolSerializer < ActiveModel::Serializer
    attributes :id, :school_specialty, :school_location
end

In my app/controllers/api/v1/schools.rb i have:

module API
    module V1
        class Schools < Grape::API
            include API::V1::Defaults

            resource :schools do
.................
.................
other crud endpoints which are working perfectly
.................
.................
             desc "Search for schools"
                params do
                    requires :specialty, type: String, desc: "school specialty"
                    requires :search_location, type: String
                end
                get "search", root: "schools" do
                    School.where("school_specialty = ? AND school_location = ?", permitted_params[:specialty], permitted_params[:search_location]).order("RANDOM()")
                end
            end
        end
    end
end

On web without grape this search functionality is working perfectly but via API i get this error response:

{
   "error": "Couldn't find School with [WHERE \"schools\".\"id\" = ?]"
}

i have run out of ideas. I cant find any helpful pointers after searchhing for weeks now. I am beginning to think it is not possible to directly search database. It seems I have to fetch all the records and then filter the results in my app. Any help will be greatly appreciated. thanks.

Answers to

Is it possible to filter (search) results at query level when using grape gem in Rails 4 app?

Source Show
◀ Wstecz