LoginSignup
233
180

More than 5 years have passed since last update.

rails helper 基本

Posted at

helperとは

view内でちょっとした処理をやりたい時に使う。viewをシンプルにする為に。
viewと別の場所(helper)で定義しておいたメソッドをviewから呼び出すことができる。

作成方法

rails g controllerを実施した際に作成される

rails g controller Test
#↓
create  app/helpers/test_helper.rb
create  app/controllers/test_controller.rb

helperの実体

実体はmodule。
ソースを見るとmoduleが生成されていることがわかる。

test_helper.rb
module TestHelper
end

helperのinclude

moduleなのでincludeして使う必要がある。
ただしそれは自動的にやってくれる。

  • rails5ではデフォルトは、全てinclude。
 By default, each controller 
   # will include all helpers. These helpers are only accessible on the controller through <tt>#helpers</tt> |
   # 
   # In previous versions of \Rails the controller will include a helper which |
   # matches the name of the controller, e.g., <tt>MyController</tt> will automatically |
   # include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+. 
  • コントローラに対応するものしか読み込ませたくない時は、config/application.rbに以下設定をする
config/application.rb
module xxx
  class Application < Rails::Application
    config.action_controller.include_all_helpers = false #これをセット!!
  end
end

helperの呼び出し

  • viewでhelperで定義したメソッド名を指定するだけ
Atest_helper
module AtestHelper
  def test
    "testA"
  end
end
viewで呼び出す
<h1><%= test %> #testAが表示される
  • 異なるヘルパーファイルで同名のメソッドがある場合は注意

helperを全てincludeしていると意図していないメソッドが呼ばれる可能性があるので注意。
以下のようなケース。

Atest_helper
module AtestHelper
  def test
    "testA"
  end
end
Btestb_helper
module BtestHelper
  def test
    "testB"
  end
end
view
# AtestHelperかBtestHelperどちらが呼ばれるか分からない
<h1><%= test %></h1>
233
180
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
233
180