Rails - 如何在控制器内使用助手

发布于 2024-10-19 04:11:55 字数 363 浏览 2 评论 0原文

虽然我意识到您应该在视图中使用助手,但我在控制器中需要一个助手,因为我正在构建要返回的 JSON 对象。

它有点像这样:

def xxxxx

   @comments = Array.new

   @c_comments.each do |comment|
   @comments << {
     :id => comment.id,
     :content => html_format(comment.content)
   }
   end

   render :json => @comments
end

如何访问我的 html_format 帮助程序?

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:

def xxxxx

   @comments = Array.new

   @c_comments.each do |comment|
   @comments << {
     :id => comment.id,
     :content => html_format(comment.content)
   }
   end

   render :json => @comments
end

How can I access my html_format helper?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

不知所踪 2024-10-26 04:11:55

您可以

  • Rails 5+ 中使用 helpers.(或 ActionController::Base.helpers.
  • view_context. (Rails 4 & 3)(警告:这会在每次调用时实例化一个新的视图实例)
  • @template. (Rails 2)
  • 在单例类中包含帮助器,然后
  • 在控制器中包含 singleton.helper 包含 帮助器(警告:将使所有帮助器方法转化为控制器动作)

You can use

  • helpers.<helper> in Rails 5+ (or ActionController::Base.helpers.<helper>)
  • view_context.<helper> (Rails 4 & 3) (WARNING: this instantiates a new view instance per call)
  • @template.<helper> (Rails 2)
  • include helper in a singleton class and then singleton.helper
  • include the helper in the controller (WARNING: will make all helper methods into controller actions)
深海蓝天 2024-10-26 04:11:55

注意: 这是在 Rails 中编写并接受的 2 天;现在grosser的答案是要走的路。

选项 1: 可能最简单的方法是将辅助模块包含在控制器中:

class MyController < ApplicationController
  include MyHelper
    
  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

选项 2: 或者您可以将辅助方法声明为类函数,然后像这样使用它: so:

MyHelper.html_format(comment.content)

如果您希望能够将它用作实例函数和类函数,您可以在助手中声明这两个版本:

module MyHelper
  def self.html_format(str)
    process(str)
  end
    
  def html_format(str)
    MyHelper.html_format(str)
  end
end

Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

Option 1: Probably the simplest way is to include your helper module in your controller:

class MyController < ApplicationController
  include MyHelper
    
  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2: Or you can declare the helper method as a class function, and use it like so:

MyHelper.html_format(comment.content)

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

module MyHelper
  def self.html_format(str)
    process(str)
  end
    
  def html_format(str)
    MyHelper.html_format(str)
  end
end
屋顶上的小猫咪 2024-10-26 04:11:55

在 Rails 5 中,请在控制器中使用 helpers.helper_function

示例:

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

来源:来自 @Markus 对不同答案的评论。我觉得他的答案应该有自己的答案,因为它是最干净、最简单的解决方案。

参考:https://github.com/rails/rails/pull/24866

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

残龙傲雪 2024-10-26 04:11:55

我的问题通过选项 1 解决。可能最简单的方法是将辅助模块包含在控制器中:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...

My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...
原来是傀儡 2024-10-26 04:11:55

一般来说,如果助手要在(仅)控制器中使用,我更喜欢将其声明为 class ApplicationController 的实例方法。

In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController.

乱世争霸 2024-10-26 04:11:55

在 Rails 5 之前,您必须包含辅助模块。

在较新的版本中,您可以将控制器中的助手与助手(复数)对象一起使用。

  class UsersController
    def index
      helpers.my_helper_method_name(even_pass_arg_here)
    end
  end

https://www.rubyguides.com/2020/01/rails-helpers/

Before Rails 5, you have to include the helper module.

In newer versions, you can use helpers in your controller with the helpers (plural) object.

  class UsersController
    def index
      helpers.my_helper_method_name(even_pass_arg_here)
    end
  end

https://www.rubyguides.com/2020/01/rails-helpers/

萧瑟寒风 2024-10-26 04:11:55

在 Rails 5+ 中,您可以简单地使用该函数,如下面的简单示例所示:

module ApplicationHelper
  # format datetime in the format #2018-12-01 12:12 PM
  def datetime_format(datetime = nil)
    if datetime
      datetime.strftime('%Y-%m-%d %H:%M %p')
    else
      'NA'
    end
  end
end

class ExamplesController < ApplicationController
  def index
    current_datetime = helpers.datetime_format DateTime.now
    raise current_datetime.inspect
  end
end

输出

<前><代码>“2018-12-10 01:01 AM”

In Rails 5+ you can simply use the function as demonstrated below with simple example:

module ApplicationHelper
  # format datetime in the format #2018-12-01 12:12 PM
  def datetime_format(datetime = nil)
    if datetime
      datetime.strftime('%Y-%m-%d %H:%M %p')
    else
      'NA'
    end
  end
end

class ExamplesController < ApplicationController
  def index
    current_datetime = helpers.datetime_format DateTime.now
    raise current_datetime.inspect
  end
end

OUTPUT

"2018-12-10 01:01 AM"
陪我终i 2024-10-26 04:11:55

在 Rails 6 中,只需将其添加到控制器中:

class UsersController < ApplicationController
  include UsersHelper
  
  # Your actions

end

现在 user_helpers.rb 将在控制器中可用。

In rails 6, simply add this to your controller:

class UsersController < ApplicationController
  include UsersHelper
  
  # Your actions

end

Now the user_helpers.rb will be available in the controller.

遗失的美好 2024-10-26 04:11:55

其他答案中缺少的一个替代方案是您可以采取相反的方式:在控制器中定义您的方法,然后使用 helper_method 使其也可以作为辅助方法在视图上使用。

例如:


class ApplicationController < ActionController::Base

private

  def something_count
    # All other controllers that inherit from ApplicationController will be able to call `something_count`
  end
  # All views will be able to call `something_count` as well
  helper_method :something_count 

end

One alternative missing from other answers is that you can go the other way around: define your method in your Controller, and then use helper_method to make it also available on views as, you know, a helper method.

For instance:


class ApplicationController < ActionController::Base

private

  def something_count
    # All other controllers that inherit from ApplicationController will be able to call `something_count`
  end
  # All views will be able to call `something_count` as well
  helper_method :something_count 

end
娇妻 2024-10-26 04:11:55
class MyController < ApplicationController
    # include your helper
    include MyHelper
    # or Rails helper
    include ActionView::Helpers::NumberHelper

    def my_action
      price = number_to_currency(10000)
    end
end

在 Rails 5+ 中,只需使用 helpers (helpers.number_to_currency(10000))

class MyController < ApplicationController
    # include your helper
    include MyHelper
    # or Rails helper
    include ActionView::Helpers::NumberHelper

    def my_action
      price = number_to_currency(10000)
    end
end

In Rails 5+ simply use helpers (helpers.number_to_currency(10000))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文