Ruby on rails ActiveModel序列化程序发送所有记录而不是指定的有限数量
我有一个控制器,看起来像这样:Ruby on rails ActiveModel序列化程序发送所有记录而不是指定的有限数量,ruby-on-rails,ruby,ember.js,ember-data,active-model-serializers,Ruby On Rails,Ruby,Ember.js,Ember Data,Active Model Serializers,我有一个控制器,看起来像这样: class MetricsController < ApplicationController def index org = current_user.organization metrics = Metric.where(organization: org).last(100) render json: metrics, status: 200, include: [:organization] end end 正如您所
class MetricsController < ApplicationController
def index
org = current_user.organization
metrics = Metric.where(organization: org).last(100)
render json: metrics, status: 200, include: [:organization]
end
end
正如您所看到的,我的序列化程序正在吐出度量表中的每一条记录,而我大概只需要最后100条记录。我不确定我在AMS(0.8)中设置的错误是什么
有趣的是,我的rails控制台显示了具有正确限制的正确SQL:
Metric Load (0.7ms) SELECT "metrics".* FROM "metrics" ORDER BY "metrics"."id" DESC LIMIT 100
Organization Load (0.3ms) SELECT "organizations".* FROM "organizations" WHERE "organizations"."id" = $1 LIMIT 1 [["id", 1]]
查看以下网站上的指南:
默认情况下,序列化程序只需查找原始对象上的关联。您可以通过实现名为关联的方法并返回不同的数组来自定义此行为
因此,每个模型都会根据其序列化程序进行序列化。您的组织
模型正在通过您的组织序列化程序
,该程序已指定了多个:指标。因此,rails查找了该组织的所有指标,并对它们进行了序列化
你不想这样,你只是关心这个指标所属的一个组织。因此,只要删除该行,rails就不会序列化其余部分。我很困惑;看起来JSON输出可能来自OrganizationsController
,而不是MetricsController
。至少,根元素是组织
,而不是度量
。您可以发布一个请求的示例,它将为您提供指定的输出吗?\n谢谢Sam-我有一个OrganizationSerializer
,并更新了我的问题以包含它。也就是说,我仍然有这个问题。只有render json:metrics.to_json,status:200才能解决这个问题!哦,您声明了模型上有许多关联,但在序列化中定义了关联。
class Organization < ActiveRecord::Base
has_many :metrics
end
class MetricSerializer < ActiveModel::Serializer
embed :ids
attributes :id, :provisioned_users, :connected_users, :created_at
has_one :organization
end
class OrganizationSerializer < ActiveModel::Serializer
attributes :id, :name, :org_id, :gauth_enabled
has_many :metrics
end
organizations: [
{
id: 1,
name: "ACME",
org_id: "org_id232323",
gauth_enabled: "f",
metric_ids: [
1,
2,
3,
...
1000
]
}
],
Metric Load (0.7ms) SELECT "metrics".* FROM "metrics" ORDER BY "metrics"."id" DESC LIMIT 100
Organization Load (0.3ms) SELECT "organizations".* FROM "organizations" WHERE "organizations"."id" = $1 LIMIT 1 [["id", 1]]