作为服务对象在视图中显示消息

时间:2014-09-15 10:32:06

标签: ruby-on-rails

我做了一个服务对象: 应用程序/服务/ result_service.rb

class ResultService
  def initialize(number_of_errors)
    if number_of_errors == 0
      flash[:success] = "0 error"
      card.update_review_date
    elsif number_of_errors == 1
      flash[:error] = "1 error"
    elsif number_of_errors == 2
      flash[:error] = "2 errors"
    elsif number_of_errors == 3
      flash[:error] = "3 errors"
    else number_of_errors == 4
      flash[:error] = "4 or more of errors"
    end
  end
end

它处理来自控制器的传入参数。

如果我按照上面的指示留下flash消息,则会产生错误:

undefined local variable or method `flash' for #<ResultService:0x007fd6488bf080>

如何携带Flash消息? 我建议这可以通过views helper来完成。 怎么做?

2 个答案:

答案 0 :(得分:0)

抱歉,您可以使用特殊方法:

pluralize(object.errors.count, "error")

或者在你的情况下通知:

pluralize(number_of_errors, 'thing')

答案 1 :(得分:0)

为这个问题提供理想的解决方案有点困难,因为我不知道如何使用ResultService。无论如何,这个解决方案应该适合你:

class ResultService
  def initialize(number_of_errors, controller)
    if number_of_errors == 0
      controller.flash[:success] = "0 error"
      card.update_review_date
    elsif number_of_errors == 1
      controller.flash[:error] = "1 error"
    elsif number_of_errors == 2
      controller.flash[:error] = "2 errors"
    elsif number_of_errors == 3
      controller.flash[:error] = "3 errors"
    else number_of_errors == 4
      controller.flash[:error] = "4 or more of errors"
    end
  end
end

# somewhere in controller
ResultService.new(number_of_errors, self)

此方法称为Dependency Injection