1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ヘルパーメソッドの利用

Posted at

railsのヘルパーメソッド

railsにはview内でちょっとした処理などを行う際に呼び出したいメソッドをviewとは別の場所に定義しておき、view内で呼び出すことができる。
記載場所はapp/helper/コントローラ名_helper.rb
rails g controllerで作成した際にこのhelperファイルは自動生成される。
これはmoduleとして作られており、読み込みはrails5であれば自動で読み込んでくれる。

問題

ヘルパーメソッドを定義して入力された価格を3桁ごとに区切り円を付けて出力するコードを実装する問題があったとする。

app/helper/production.rb
module ProductsHelper
  def converting_to_jpy(price)
    "#{price.to_s(:delimited, delimiter: ',')}円"
  end
end

このようにヘルパーメソッドとして定義する。
viewでの呼び出しは

index
前後省略
<td><%= converting_to_jpy(product.price) %></td>

このようにメソッドを呼び出すだけである。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?