Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 限制返回的JSON行数_Ruby On Rails_Activerecord_Ruby On Rails 3.2 - Fatal编程技术网

Ruby on rails 限制返回的JSON行数

Ruby on rails 限制返回的JSON行数,ruby-on-rails,activerecord,ruby-on-rails-3.2,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

假设在控制器中,我们有如下内容:

@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_计数,那么返回的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

为什么不能让模型将数据集返回给您,并附带您所拥有的条件,这样您就不必使用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

因为我没有足够的知识!你能再解释一下吗?我的模型很空,只是一堆有很多,属于程序和患者计数模型。谢谢你的示例答案。如果我想说薪资领域的“前20名”是什么?(即列出薪资最高的前20名人员)如果您只想获得薪资,请仅根据薪资条件修改范围,并将限制保持在20人。默认情况下,它将从表中选择满足您薪资标准的前20名。您能用您的models@AnkitG谢谢先生的关注,好的,我更新了模型。
Program.includes(:patient_counts).salary_and_bonus(15,20) #15 and 20 are my assumed limits