Rails 4 + Serialization:禁用ActiveModel :: Serializer进行查看

时间:2017-08-23 15:47:54

标签: ruby-on-rails serialization active-model-serializers

我有一个带有搜索功能的API,它返回client个对象的列表。通常我喜欢使用我的client序列化程序来控制返回哪些属性。但是,在搜索时,我希望减少attributes次,以便更快地完成搜索。

我的控制器

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无效,因为我的日志显示每个返回的client抓取了我不需要的所有关联,并且在整个日志中仍显示active_model_serializers

登录

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]]

如何防止加载其他属性?

1 个答案:

答案 0 :(得分:0)

我可以通过更改以下行来解决我的问题:

paginate json: @clients, serializer: nil, per_page: 25

为:

paginate json: @clients, adapter: false, per_page: 25