2

I am getting a parameter e.g: member_id in Grape::API like

   desc 'Return Events'
         params do
             requires :member_id, type: Integer, desc: 'Member'
         end
         get 'all' do
              #some code
         end
     end

and I want to pass it to ActiveModel::Serializer so that I can perform some functionality.

Is there any way that I can pass it to ActiveModel::Serializer?

almcd
  • 1,069
  • 2
  • 16
  • 29
Muhammad Faisal Iqbal
  • 1,796
  • 2
  • 20
  • 43

1 Answers1

3

When you serialize an object using ActiveModel::Serializers, you can pass along options which are available inside the serializer as options (or instance_options, or context, depending on which version of AMS you're using).

For instance, in Rails you would pass a foo option like so:

# 0.8.x or 0.10.x
render @my_model, foo: true
MyModelSerializer.new(@my_model, foo: true).as_json

# 0.9.x
render @my_model, context: { foo: true }
MyModelSerializer.new(@my_model, context: { foo: true }).as_json

In your serializer you access options (or instance_options) to get the value:

class MyModelSerializer < ActiveModel::Serializer
  attributes :my_attribute

  def my_attribute
    # 0.8.x: options
    # 0.9.x: context
    # 0.10.x: instance_options
    if options[:foo] == true
      "foo was set"
    end
  end
def
gmcnaughton
  • 2,233
  • 1
  • 21
  • 28
  • in both cases options[:current_family] and instance_options[:current_family] it says it don't know options or instance_options – Muhammad Faisal Iqbal Oct 07 '16 at 15:47
  • Tricky! Sorry about that - which version of AMS are you on? – gmcnaughton Oct 07 '16 at 16:51
  • active_model_serializers (0.9.5) and grape-active_model_serializers (1.3.2), actually in gem file I 've just written "grape-active_model_serializers" – Muhammad Faisal Iqbal Oct 07 '16 at 18:07
  • Unfortunately 0.9.x differs substantially from 0.8.x and 0.10.x. 0.9.x requires custom options to be nested under a `context` key, and you use `context` instead of `instance_options` to access them. – gmcnaughton Oct 08 '16 at 16:27
  • I didn't get it, tried some search about context in serializer but didn't find something usefull. can you explain it a little – Muhammad Faisal Iqbal Oct 08 '16 at 17:41
  • I updated the example code in the answer above - try `MyModelSerializer.new(@my_model, context: { foo: true }).as_json` and `if context[:foo] == true` in your serializer. – gmcnaughton Oct 08 '16 at 19:06
  • @gmcnaughton How do I access the current_user in the serializer? When I do MyModelSerializer.new( it does not let me access the current_user. – Sakshi Jain Jun 29 '22 at 13:23