Question

I want to customize json output of my ActiveModel instance with as_json method. But though pass whitelist of attributes in only option, the result includes all attributes.

Here is example:

class Foo
  include ActiveModel::Model
  attr_accessor :a, :b
end  

Foo.new(a: 1, b: 2).as_json
# {"a" => 1, "b" => 2}

Foo.new(a: 1, b: 2).as_json(only: [:a])
# {"a" => 1, "b" => 2}
# but I expect {"a" => 1}

Is it I doing something wrong?

Était-ce utile?

La solution

I forgot include ActiveModel::Serializers::JSON module and attributes method. After this fix all work as expected:

class Foo
  include ActiveModel::Model
  include ActiveModel::Serializers::JSON
  attr_accessor :a, :b

  def attributes
    {'a' => nil, 'b' => nil}
  end  
end  

Foo.new(a: 1, b: 2).as_json
# {"a" => 1, "b" => 2}

Foo.new(a: 1, b: 2).as_json(only: [:a])
# {"a" => 1}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top