Reputation: 6684
I have an API with a search function that returns a list of client
objects. Normally I like to use my client
serializer to control which attributes are returned. However, when searching, I'd like to require fewer attributes
so that the search can be completed more quickly.
My controller
def index
@clients = Client.order("created_at ASC")
if params[:search].present?
@clients = Client.select('name', 'id').where("(name like ?) OR (name like ?)", "%#{params[:search]}%", "%#{params[:search].titleize}%")
end
paginate json: @clients, serializer: nil, per_page: 25
end
serializer: nil
has no effect because my logs show each returned client
grabbing all it's associations that I don't need and still shows active_model_serializers
throughout the log.
log
Client Load (0.8ms) SELECT "clients"."name", "clients"."id" FROM "clients" WHERE ((name like '%ta%') OR (name like '%Ta%')) LIMIT 25 OFFSET 0
# I don't need any of this (below)
[active_model_serializers] CheckIn Load (1.3ms) SELECT "check_ins".* FROM "check_ins" WHERE "check_ins"."client_id" = $1 ORDER BY created_at ASC [["client_id", 1363]]
[active_model_serializers] Payment Load (0.1ms) SELECT "payments".* FROM "payments" WHERE "payments"."client_id" = $1 [["client_id", 1363]]
[active_model_serializers] Purchase Load (0.1ms) SELECT "purchases".* FROM "purchases" WHERE "purchases"."client_id" = $1 [["client_id", 1363]]
[active_model_serializers] Program Load (0.2ms) SELECT "programs".* FROM "programs" WHERE "programs"."client_id" = $1 [["client_id", 1363]]
What can I do to prevent the additional attributes from being loaded?
Upvotes: 1
Views: 838
Reputation: 6684
I was able to solve my problem by changing the following line:
paginate json: @clients, serializer: nil, per_page: 25
to:
paginate json: @clients, adapter: false, per_page: 25
Upvotes: 1