Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save necojackarc/7b69cda6c61d2a67b05a5f037e889d41 to your computer and use it in GitHub Desktop.
Save necojackarc/7b69cda6c61d2a67b05a5f037e889d41 to your computer and use it in GitHub Desktop.
How to Use ActiveModelSerializers inside Jbuilder
options = { scope: current_user, scope_name: :current_user }
json.users ActiveModelSerializers::SerializableResource.new(@users, options)

Background

ActiveModelSerializers (AMS) is often said "an alternative to Jbuilder", but AMS is a kind of decorator which knows only how to serialize the target objects. On the other hand, Jbuilder is a library for the view of MVC.

So, it's a bit tough with only AMS to compose complex JSONs like this:

{
  "users": [
  ],
  "aminals": [
  ],
  "insects": [
  ]
}

because AMS objects don't know how to make an entire response; they have concerns just about their target objects.

In this case, using Jbuilder is one solution (I never say the best solution) as follows:

# app/controllers/creatures_controller.rb
class CreaturesController
  def index
    @users = User.all
    @animals = Animal.all
    @insects = Insect.all
  end
end

# app/views/creatures/index.json.jbuilder
json.users ActiveModelSerializers::SerializableResource.new(@users)
json.animals ActiveModelSerializers::SerializableResource.new(@animals)
json.insects ActiveModelSerializers::SerializableResource.new(@insects)

How-to

Pass scope and scope_name as options to designate them as current_user when initializing ActiveModelSerializers::SerializableResource:

options = { scope: current_user, scope_name: :current_user }
json.resources ActiveModelSerializers::SerializableResource.new(@resources, options)

References

class UserSerializer
attributes :id, :username
attribute :email, if: :current_user?
def current_user?
current_user.id == object.id
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment