限制返回的JSON行数

时间:2013-03-02 21:51:08

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

让我们说在控制器中我们有这样的东西:

@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个patient_counts,那么返回的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

1 个答案:

答案 0 :(得分: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