ruby-on-railsruby-on-rails-4grape-api

Grape how to set param values dynamically


We have been using grape for a long time.

Below is how we set values for a param.

params do
  optional :my_column1, type: Integer, desc: 'some description', values: MyModel1.all.pluck(:id)
  optional :my_column2, type: Integer, desc: 'some description', values: MyModel2.all.pluck(:id)
end

Our database is shared between two services. The above two columns(my_column1 and my_column2) get updated by other microservice. And when someone makes a request using API, it fails with the error message "my_column1 does not have a valid value.". same goes for my_column2.

While debugging I realized that during booting of rails application these values are being set and it only gets updated when we restart the server next time.

What we want are these values to be updated dynamically. Which means every time we make a request, it should make a query to the database and set those values. I am having a very hard time figuring out how to do this, or even if it's possible with Grape.

Any help will be appreciated.


Solution

  • You just need to move the values into a proc, so that they are evaluated on each request:

    params do
      optional :my_column1, type: Integer, values: -> { MyModel1.all.pluck(:id) }
    end
    

    This is covered in more detail in the main README here: https://github.com/ruby-grape/grape#values