我在params [:医院]中列出了两家医院的键值选择,我试图在下面的查询中使用params [:hospital]编写一个条件来条件行。
params[:hospitals].each do |hospital, xyz|
<!--code -->
Condition.find_by_hospital_id(Hospital.find_by_hospital_name(hospital).id)//query
Params包含
{"utf8"=>"✓",
"authenticity_token"=>"",
"client"=>{"Client1"=>"1"},
"hospital"=>{"hospital1"=>"Client1", "hospital2" => "client2"},
"type"=>"BOTH",
"beg-dt-tm"=>"",
"datepicker"=>"",
"end-dt-tm"=>"",
"controller"=>"",
"action"=>""}
我的问题:是否有更好的方法通过避免多次调用表来编写查询
由于
答案 0 :(得分:4)
如果医院有很多条件:
class Hospital < ActiveRecord::Base
has_many :conditions
end
然后你应该能够在一个查询中加载所有内容:
hospitals = Hospital.where(hospital_name: params[:hospitals]).includes(:conditions)
hospitals.each do |hospital|
# no further SQL queries will be run, because the conditions have been preloaded
hospital.conditions.each do |condition|
# do something with this condition
end
end
答案 1 :(得分:2)
只需进行两次查询。首先按名字加载所有医院,第二个加载所有医院条件。看起来应该是这样的:
hospitals = Hospital.where(hospital_name: params[:hospitals])
conditions = Condition.where(hospital_id: hospitals)
在这种情况下,只会执行两次DB查询。