1

I have mounted grape gem over exsting application & in kept grape api related changes in

app >> controller >> api

directory. (which is auto loaded. No code is written for autoloading)

And in that I have code like fetching values form the database table.

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

      resource :users do

        desc 'Creates a User'
        params do
          requires :role_id,
            type: Integer,
            values: Role.all.collect { |role| role.id },
            desc: 'Role ID'

Here Role.all getting called while setting up new application, which is doesn't exists yet.

But while setting up new application, when I run "rake db:migrate" it gives table doesn't exists error.

How can I stop auto loading of the "api" folder inside controller while setting up new application so that it will not get called.

Or how can I handle above scenario.

& application.rb file where defined grape

module Api
  class Application < Rails::Application
    config.middleware.use Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get,
          :post, :put, :delete, :options]
      end
    end
  end
end

Thanks in advance.

Akash Kinwad
  • 704
  • 2
  • 7
  • 22

1 Answers1

0

Above problem was solved by using lazy evaluation of the values.

Used proc for grape values

The :values option can also be supplied with a Proc, evaluated lazily with each request.

and reframed code will be as below

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

      resource :users do

        desc 'Creates a User'
        params do
          requires :role_id,
            type: Integer,
            values: -> { Role.all.collect { |role| role.id } },
            desc: 'Role ID'

We can also use class methods inside proc to fasten the query.

Akash Kinwad
  • 704
  • 2
  • 7
  • 22