2
votes

I have a custom model "Result" as shown below where in its attributes groups and categories are active-record models having id, created_at, updated_at.

class Result
  attr_accessor :groups, :categories
end

when to_json is invoked on Result object with :except[:id, :created_at, :updated_at] method on groups and categories, there is no effect, the JSON output constructed contains id, created_at and updated_at.

Please help me out in constructing the proper conditional to_json to get JSON output without id, created_at, updated_at on groups and categories.

Example:

result = Result.new
result.groups = groups
result.categories = categories

result.to_json(:include => {
  :groups => {:except => [:id, :created_at, :updated_at]},
  :categories => {:except => [:id, :created_at, :updated_at]}
})
1

1 Answers

3
votes

None of those statements that you have in to_json is being taken into account on serialization.

As per this page, in order for those :exclude, :include, :only statements to work, you have to do the following (since you are not extending ActiveRecord::Base):

class Result
  include ActiveModel::Serializers::JSON

  attr_accessor :groups, :categories

  def attributes
    {'groups' => groups, 'categories' => categories}
  end
end

Same goes for classes in groups and categories.