【问题标题】:Moving logic out of my view for a rails app将逻辑移出我对 Rails 应用程序的视图
【发布时间】:2011-03-25 19:42:09
【问题描述】:

好的,所以基本上我编写了这个应用程序,它对部分的每个点进行一些计算。这部分代码在控制器内处理,所以没关系。问题是我需要一些计算结果显示在屏幕上,以便我可以打印(到纸上)任何内容

    <h2>Output for error calculations</h2>

<%
@sections.each_with_index do |section, sindex|

    # Retrieve our values
    total_distance = @total_distances[sindex]
    @total_points_calc = @total_points_sections[sindex]
    total_points = section.points.count

%>
    <h3>Section <i><%= section.name %></i></h3>
    <hr>
    <p>\( \Sigma d_{<%= section.name %>} = <%= section.name %> \)</p>
    <p>
        \( \Sigma d_{<%= section.name %>}= \)
        <% 
        section.points.each_with_index do |point, index| %>
                <%=                 
                 # if this isn't the first section and the point.distance is 0
         sindex != 0 and point.distance == 0 ? point.distance = nil : point.distance = point.distance

                 # add a + after each point that isn't the last
                 index != @total_points_calc ? point.distance.to_s + ' +' : point.distance
                %>
        <% end %>
        = <%= total_distance%>
    </p>
    <p>
    \( <%= section.name %>= \) <%= section.length %>
    </p>
    <p>e = \( \frac{<%= total_distance %> - <%= section.length %>}{<%= @total_points_calc %>} \) = <%= @errors[sindex] %></p>
<% end %>

这是一些示例输出http://img35.imageshack.us/i/screenshot20110325at133.png/ 完整的源代码可以在http://github.com/carvefx/Roadie找到。

我将如何以真正的 Rails 精神将这种逻辑的(部分)从视图中移开。看起来很奇怪的语法是 LaTeX,我需要它来在网络上输出数学。

【问题讨论】:

    标签: ruby-on-rails view logic


    【解决方案1】:

    有几种方法可以将代码移动到其他地方。如果它属于控制器,那么您可以将其移动到控制器代码中,可能使其成为受保护的方法。

    如果是帮助创建视图,对于一些通用的方法,可以使用helper,比如application helpers。 (或特定于该视图的助手)

    如果某些逻辑属于DB中的数据,那么你可以把它移到模型中,也就是让它成为一个“瘦控制器,胖模型”:http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model

    【讨论】:

    • 读起来很有趣,谢谢!在这种情况下无法真正应用它,因为控制器已经进行了计算,这样就有意义了。这部分代码“什么都不做”——它只是以某种方式显示信息。最后,我稍微清理了代码,并在每个循环的中心使用了部分代码。
    猜你喜欢
    • 2016-03-25
    • 2012-07-18
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    相关资源
    最近更新 更多