【问题标题】:cleaner way of moving the total count logic in a ruby helper在红宝石助手中移动总计数逻辑的更干净的方法
【发布时间】:2013-11-19 10:54:40
【问题描述】:

这是一个有点愚蠢的问题,但我有点在寻找一种很好的方法来将它放入辅助方法或其他东西中。 我循环播放游戏并获取每个事件的总数和获胜计数方法。 并将整个东西加在一起并显示。

- count = 0
- win_count = 0
- game.results.each do |result|
  - count+=result.total
  - win_count+=result.wins

="total wins#{win_count}"
="total#{count}"

有没有更好的红宝石方法?

注意:我需要一个不使用模型的解决方案。

【问题讨论】:

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


    【解决方案1】:

    当然有更好的方法,更好的方法是使用Model的方法,而不是helper。尽可能避免使用助手。

    class Game < ActiveRecord::Base
      has_many :results
    
      def winning_count
        wining_results.count
      end
    
      def winding_results
        results.where(win: true)
      end
    
      def results_count
        results.count
      end
    
    end
    

    视图中的用法

    @game.results_count
    @game.winning_count
    

    【讨论】:

    • 问题是这个应用没有模型。外部服务正在重新调整 json 中的结果。
    • @newbie 您可以围绕 json 响应数据创建一个瘦包装器(一个表示模型)。将您需要的任何逻辑添加到演示模型中。我经常使用这种方法。
    • 同意@WizardofOgz 使用服务对象/演示者。很棒的文章在这里:blog.codeclimate.com/blog/2012/10/17/…(特别是#2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2015-03-21
    相关资源
    最近更新 更多