Reputation: 26919
Let's say in the controller we have something like this:
@org = Org.includes(programs: :patient_counts]).find(params[:id])
respond_with(@org)
and now I pass this to JBuilder:
json.program @org.programs do |program|
json.(program, :name)
# more code to also return some info from patien_counts table too
end
So if I have like 200 programs and in a 1-1 relationship I have also 200 patient_counts then the JSON that gets returned will have 200 objects. BUT in my case I only want a certain amount of them. For example I lets say patient_counts table has two fields called Salary and Bonus and I want to return 15 objects in the JSON, not all of those 200 objects..only 15 of them that have highest Salary+Bonus.
For logic and calculations like this scenario what should I do?
EDIT: Info about Models:
program.rb :
name:string
has_many: patient_conuts
patient_count.rb:
belongs_to: program
program_id # from the program above
total_amount: integer
Upvotes: 0
Views: 674
Reputation: 6568
Why can't you have the model return the dataset to you with the conditions that you are having so that you don't have to work on the JSON for filtering
Update:
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
eg
Program.includes(:patient_counts).salary_and_bonus(15,20) #15 and 20 are my assumed limits
Upvotes: 1