0

コントローラに次のようなものがあるとしましょう:

@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という2つのフィールドがあり、JSONで15個のオブジェクトを返したいとします。これらの200個のオブジェクトすべてではなく、Salary+Bonusが最も高いのは15個だけです。

このシナリオのようなロジックと計算の場合、どうすればよいですか?

編集:モデルに関する情報:

program.rb :
name:string
has_many: patient_conuts

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

1 に答える 1

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
于 2013-03-02T22:19:29.013 に答える