Rails - How to use a Helper Inside a Controller

前端 未结 8 1242
生来不讨喜
生来不讨喜 2020-11-29 15:01

While I realize you are supposed to use a helper inside a view, I need a helper in my controller as I\'m building a JSON object to return.

It goes a little like this:

8条回答
  •  臣服心动
    2020-11-29 16:05

    In Rails 5 use the helpers.helper_function in your controller.

    Example:

    def update
      # ...
      redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
    end
    

    Source: From a comment by @Markus on a different answer. I felt his answer deserved it's own answer since it's the cleanest and easier solution.

    Reference: https://github.com/rails/rails/pull/24866

提交回复
热议问题