2014-02-11 56 views
0

在我的控制器我有:組方法中只顯示一個PARAMS

@comparison = Result.group('results.trial_id').having('COUNT(results.variety_id) = 2').where('results.variety_id' => [params[:variety_one], params[:variety_two]]). 
joins(:trial).where('trials.irrigated' => params[:irrigated], 'trials.year' => params[:year]).joins(:regions).where('sites.region_id' => params[:regions]) 

當我在我的視圖檢查@comparison它僅示出了用於PARAMS結果[:variety_two],這是variety_id:2255和不PARAMS [ :variety_one]。爲什麼是這樣?

輸出鑑於

[#<Result id: 275428, trial_id: 1038, created_at: "2014-01-29 04:42:43", updated_at: "2014-01-29 04:42:43", variety_id: 2255, year: 2009, lint: 1559.0, turnout: 41>>] 

所以還應列出PARAMS [:variety_one],這是variety_id:2246爲好。

SQL

SELECT DISTINCT results.year FROM `results` INNER JOIN `trials` ON `trials`.`trial_id` = `results`.`trial_id` INNER JOIN `trials` `trials_results_join` ON `trials_results_join`.`trial_id` = `results`.`trial_id` INNER JOIN `sites` ON `sites`.`site_id` = `trials_results_join`.`site_id` INNER JOIN `regions` ON `regions`.`region_id` = `sites`.`region_id` WHERE `results`.`variety_id` IN (2246, 2255) AND `trials`.`irrigated` IN (2) AND `trials`.`year` IN ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013') AND `sites`.`region_id` IN (1, 2, 3, 4, 5, 6, 7, 8) AND `results`.`year` IN (2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013) GROUP BY results.trial_id HAVING COUNT(results.variety_id) = 2 

回答

1

免責聲明:我們一直在這個離線聊天,這就是我想你以後:

你想要得到的所有的ID爲試驗的匹配你的參數,並有這兩個品種, ,然後獲得那些有這兩個品種的試驗的所有結果?

像這樣的東西(我敢肯定,這是不是最優雅的方式,並且可以收拾):

@trial_ids = Result.where(:variety_id => [params[:variety_one], params[:variety_two]]).group(:trial_id).having('COUNT(*) = 2').count.keys 

@filtered_trials = Trial.where(:trial_id => [@trial_ids]).where('trials.irrigated' => params[:irrigated], 'trials.year' => params[:year]).joins(:regions).where('sites.region_id' => params[:regions]) 

@all = Result.where(:trial_id => [@filtered_trials.map {|x| x.trial_id}]).where(variety_id: [params[:variety_one], params[:variety_two]]).select('AVG(lint) AS lint, AVG(turnout) AS turnout') 
+0

作品一種享受。謝了哥們! – Grinskull