Ruby:在View中显示SQL结果时出现问题

时间:2014-11-13 05:04:35

标签: ruby-on-rails ruby

我在View中显示SQL结果时遇到问题。 “Place ROI”列只显示ActiveRecord:Relation ...我已经研究过,而且我对如何呈现该值感到茫然。任何帮助将不胜感激。

以下是网页上的结果:

Horse Name      Win ROI     Wins    Total Races     Place ROI
Billy the Bull  $13.3        2       2              #<ActiveRecord::Relation::ActiveRecord_Relation_Horse:0xb494fa5c> 

以下是查看代码:

<table class="table table-condensed table-bordered table-hover">
<tr>
    <th>Horse Name</th>
    <th>Win ROI</th>
    <th>Wins</th>
    <th>Total Races</th>
    <th>Place ROI</th>
</tr>
<% Horse.with_win_roi.having("#{Horse::HORSE_WIN_ROI_SELECT} > 5 and #{Horse::HORSE_NUMBER_OF_WINS} > 1").each do |horseWinROI| %>
    <tr>
        <td><%= horseWinROI.horse_name %></td>
        <td class="decimal">$<%= horseWinROI.win_roi %> </td>
        <td class="text-center"><%= horseWinROI.wins %></td>
        <td class="text-center"><%= horseWinROI.total_races %></td>
        <td>
            <%= Horse.only_place_roi.where("horses.id = ?", horseWinROI.id) %>
        </td>
    </tr>
<% end %>           
</table>

以下是型号代码:

HORSE_WIN_ROI_SELECT = "( (sum(entries.win_payoff) - (2 * count(horses.id))) / (2 * count(horses.id) ) )"
HORSE_PLACE_ROI_SELECT = "( (sum(entries.place_payoff) - (2 * count(horses.id))) / (2 * count(horses.id) ) )"

HORSE_NUMBER_OF_WINS = "SUM(CASE WHEN CAST(entries.official_finish as int) = 1 THEN 1 ELSE 0 END)"

scope :with_win_roi, -> {
    joins({:entries => {:race => [:chart,:race_level]}}).
    group("horses.id").
    select("CAST(#{HORSE_WIN_ROI_SELECT} as decimal(10,2)) as win_roi,horses.*,horses.id, #{HORSE_NUMBER_OF_WINS} as wins, #{HORSE_NUMBER_OF_RACES} as total_races").
    order("win_roi DESC")
}

scope :only_place_roi, -> {
    joins({:entries => {:race => [:chart,:race_level]}}).
    group("horses.id").
    select("CAST(#{HORSE_PLACE_ROI_SELECT} as decimal(10,2)) as place_roi")
}

1 个答案:

答案 0 :(得分:0)

我的第一个建议是take a deeper dive into ActiveRecord,因为很多这些查询肯定不是Rails做事方式。您希望尽可能避免直接编写SQL,因为这样做会跳过ActiveRecord为您执行的任何查询清理。

要回答您的问题,您的查询中发生的事情是您获得的horse表行仅包含place_roi虚拟列。要访问该列,您需要将.place_roi附加到关系中,如下所示:

Horse.only_place_roi.find(horseWinROI.id).place_roi

正如您所看到的,我还将where更改为find,因为您只想要一条记录并按ID查找。