2
2

More than 1 year has passed since last update.

【Ruby on Rails】コントローラーでヘルパーメソッドを使用する方法

Last updated at Posted at 2021-12-25

そもそもコントローラーからヘルパーを呼び出せないかな?と疑問に思ったので調べてみた。

メソッド先頭にview_contextをつけるだけ

結論、コントローラーで「view_context」をつけるだけ。

app/helpers/sample_helper.rb
module SampleHelper
  def helper_method
    # 処理の内容
  end
end
app/controllers/sample_controller.rb
class SampleController < ActionController::Base
  def index
    # 呼びたい箇所で、先頭にview_contextをつけるだけ
    view_context.helper_method
  end
end

意外とあっという間にできて安心した。

ただ、本来はビューのヘルパーを無理矢理呼び出すよりは、
アプリケーション共通処理として切り出すやり方の方が良いよう。

詳細はこちら、【Ruby on Rails】コントローラーで独自のヘルパーメソッドを使用する2つの方法を参考にしてください。

参考

【Ruby on Rails】コントローラーで独自のヘルパーメソッドを使用する方法

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2