【问题标题】:Limiting the number of JSON rows that returns限制返回的 JSON 行数
【发布时间】:2013-03-02 21:51:08
【问题描述】:

假设在控制器中我们有这样的东西:

@org = Org.includes(programs: :patient_counts]).find(params[:id])
respond_with(@org)

现在我将它传递给 JBuilder:

json.program @org.programs do |program|
  json.(program, :name)
  # more code to also return some info from patien_counts table too
end

因此,如果我有 200 个程序并且在 1-1 关系中我也有 200 个患者计数,那么返回的 JSON 将有 200 个对象。但就我而言,我只想要一定数量的它们。例如,我假设 patient_counts 表有两个名为 Salary 和 Bonus 的字段,我想在 JSON 中返回 15 个对象,而不是所有这 200 个对象......其中只有 15 个具有最高 Salary+Bonus。

对于这种情况下的逻辑和计算,我该怎么办?

编辑:关于模型的信息:

program.rb :
name:string
has_many: patient_conuts

patient_count.rb:
belongs_to: program
program_id  # from the program above
total_amount: integer

【问题讨论】:

  • 你能用你的模型更新问题吗
  • @AnkitG 感谢先生的关注,好的,我更新了模型。

标签: ruby-on-rails activerecord ruby-on-rails-3.2


【解决方案1】:

为什么你不能让模型根据你所拥有的条件将数据集返回给你,这样你就不必处理 JSON 进行过滤

更新:

class Program < ActiveRecord::Base
  has_many :patient_counts
 scope :salary_and_bonus, ->(salary,bonus) {where("salary >= :salary AND bonus >= :bonus ', {salary: salary, bonus: bonus}).limit(15)} 
end
end

例如

Program.includes(:patient_counts).salary_and_bonus(15,20) #15 and 20 are my assumed limits

【讨论】:

  • 因为我没有足够的知识!你能解释一下吗?我的模型很空,只有一堆 has_many、belongs_to 用于 program 和 patient_count 模型。
  • 感谢您的示例回答。如果我要说薪资领域的“前 20 名”是什么? (即列出薪水最高的前 20 人)
  • 如果您只想要薪水,则仅使用薪水条件修改范围并将限制保持为 20。默认情况下,它将从表中选择满足您的薪水标准的前 20 名。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多