lightsaber
lightsaber

Reputation: 1481

Rails 4: ActiveModelSerializer how to include only those records which are approved?

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

Upvotes: 0

Views: 476

Answers (3)

mhaseeb
mhaseeb

Reputation: 1779

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

Upvotes: 1

Surge
Surge

Reputation: 256

 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

Upvotes: 0

roob
roob

Reputation: 1136

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

Upvotes: 1

Related Questions