0

In my Rails 4.2 API, I'm using active model serializers for constructing json response. Suppose Post is a model and it has many comments and I only want to include comments which are approved/published. I'm using a scope called approved which gives approved comments.

JSON response for post includes all comments, how do I include records which are approved and not everything. How do I construct Post serializer for that.

class PostSerializer < ActiveModel::Serializer
  attributes :name, :body
  has_many :comments
end
lightsaber
  • 1,481
  • 18
  • 37

3 Answers3

1
class PostSerializer < ActiveModel::Serializer
  attributes :name, :body
  has_many :comments

  def comments
    object.comments.where( status: 'approved' )
  end
end

See Active Model Serializers - overriding association methods

roob
  • 1,116
  • 7
  • 11
  • It says `(lambda)> is not a symbol nor a string` – lightsaber Dec 14 '15 at 07:19
  • @StarWars my mistake. Updated. You can, of course, `scope :approved, ...` in the Comment class and use `object.comments.approved` above – roob Dec 14 '15 at 07:34
  • thanks. it worked. Is this the best/only way to do this? – lightsaber Dec 14 '15 at 07:59
  • I would say scoping from the Comment class would be a better way ( reusable and hides the implementation of the status ). I'm sure there are other ways, but 'best' really depends on trade-offs. For the sake of discussion, we can refactor to an 'ApprovedComment' class if there are sufficient reasons to do so. – roob Dec 14 '15 at 09:24
  • As of now I'm using what you've suggested in this answer, and have a `approved` scope in the model. i.e. `object.comments.approved`. – lightsaber Dec 14 '15 at 10:58
1

Overriding associations in your serializer will work. In serializer just override with this method

def comments   
  #Your comments filtering 
end

If that doesn't work then that has got to be some issue with your version of serializer. Look at this issue for more details and workarounds. https://github.com/rails-api/active_model_serializers/issues/267

Check this out too. How do I select which attributes I want for active model serializers relationships

Community
  • 1
  • 1
mhaseeb
  • 1,739
  • 2
  • 12
  • 24
0
 class PostSerializer < ActiveModel::Serializer
   attributes :name, :body
   has_many :approved_comments, -> { where status: 'approved' }, class_name: 'Comment'
 end

 PostSerializer.includes(:approved_comments)

Scoping with the approved_comments. Fetching only the comments with the status of approved. Got the concept from this http://apidock.com/rails/ActiveRecord/Associations/ClassMethods

Surge
  • 256
  • 3
  • 16