1

我这里有一些代码味道:

f.series(:name=>'Average review', :data=> [
            Integer(@review.style.reviews.average(:answer01).to_f*20),
            Integer(@review.style.reviews.average(:answer02).to_f*20),
            Integer(@review.style.reviews.average(:answer03).to_f*20),
            Integer(@review.style.reviews.average(:answer04).to_f*20),
            Integer(@review.style.reviews.average(:answer05).to_f*20),
            Integer(@review.style.reviews.average(:answer06).to_f*20),
            Integer(@review.style.reviews.average(:answer07).to_f*20),
            Integer(@review.style.reviews.average(:answer08).to_f*20),
            Integer(@review.style.reviews.average(:answer09).to_f*20),
            Integer(@review.style.reviews.average(:answer10).to_f*20),
            ]

谁能建议在单个数据库查询中处理此问题的最佳方法?

4

1 回答 1

0

好的,这不是那么简洁,但是:

@s_avgs=Style.joins(:reviews).select(
     'avg(answer01) AS avg1,
      avg(answer02) AS avg2,
      avg(answer03) AS avg3,
      avg(answer04) AS avg4,
      avg(answer05) AS avg5,
      avg(answer06) AS avg6,
      avg(answer07) AS avg7,
      avg(answer08) AS avg8,
      avg(answer09) AS avg9,
      avg(answer10) AS avg10'
      ).where(:id=>@review.style.id).first

...

f.series(:name=>'Average review for this style', :data=> [
        Integer(@s_avgs.avg1.to_f*20),
        Integer(@s_avgs.avg2.to_f*20),
        Integer(@s_avgs.avg3.to_f*20),
        Integer(@s_avgs.avg4.to_f*20),
        Integer(@s_avgs.avg5.to_f*20),
        Integer(@s_avgs.avg6.to_f*20),
        Integer(@s_avgs.avg7.to_f*20),
        Integer(@s_avgs.avg8.to_f*20),
        Integer(@s_avgs.avg9.to_f*20),
        Integer(@s_avgs.avg10.to_f*20),
        ] ) 

如果其他人有更好的选择,请告诉我!

于 2013-04-21T03:31:15.957 回答