在Rails中平均问题

时间:2014-02-04 22:38:23

标签: ruby-on-rails ruby-on-rails-3.2

我在使用rails应用中的列平均值时遇到了一些问题。它似乎是针对两个trial_id品种而不是所有选定品种的平均值。

例如。

trial_id | params[:variety_one] | params[:variety_two] |  Lint

  348    |        2300          |                      |  3.40
  348    |                      |        2555          |  5.40

所以上面的例子,当我在我的视图中调用我想要列出variety_one的平均lint时,它给了我4.40,这是variety_one(2300)和two(2555)的平均值只列出3.40的平均值。

控制器

@comparison = Result.group('results.trial_id').having('COUNT(*) = 2').where(variety_id: [params[:variety_one], params[:variety_two]]).
   joins(:trial).where('trials.irrigated' => params[:irrigated], 'year' => params[:year]).joins(:regions).where('sites.region_id' => params[:regions])
@vone = @comparison.where(params[:variety_one]).select('AVG(lint) AS lint')
@vtwo = @comparison.where(params[:variety_two]).select('AVG(lint) AS lint')
@count = @comparison.count('DISTINCT results.trial_id')
@years = @comparison.where('results.year' => params[:year]).select('DISTINCT results.year')
@region = @comparison.where('sites.region_id' => params[:regions]).joins(:regions).group('regions.region_id').select("DISTINCT regions.name")

查看

<% @vone.each do |vone| %>
<%= "%.2f" % (vone.lint/227) %></td>
<% end %>
<% @vtwo.each do |vtwo| %>
<%= "%.2f" % (vtwo.lint/227) %>
<% end %>

1 个答案:

答案 0 :(得分:1)

我在这里看到的问题是:

@vone = @comparison.where(params[:variety_one]).select('AVG(lint) AS lint')
@vtwo = @comparison.where(params[:variety_two]).select('AVG(lint) AS lint')

您错过了在where参数中添加列名称。尝试将其更新为:

@vone = @comparison.where(variety_id: params[:variety_one]).select('AVG(lint) AS lint')
@vtwo = @comparison.where(variety_id: params[:variety_two]).select('AVG(lint) AS lint')