LoginSignup
2
0

More than 1 year has passed since last update.

Ruby on Rails パーシャルとヘルパー

Posted at

初めに

ヘルパーパーシャルの使い方
違いを紹介
基本は備忘録

ヘルパー

viewをよりシンプルにDRYに書くためのモジュール
app/helpers/<コントローラ名>_helper.rb
moduleになっていてviewから呼び出せる
link_torender等がヘルパーに該当し、独自に定義もできる
*
includeが必要な時**
ControllerやModelで使う時はincludeが必要

  # 例
  module ApplicationHelper

  # ページごとの完全なタイトルを返します。
  def full_title(page_title = '')
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
      base_title
    else
      page_title + " | " + base_title
    end
  end

end

Controllerで使う時

class ApplicationController < ActionController::Base
  # include <Helper名>
  # app/controllers/helpersと拡張子は省略できる
  # ApplicationControllerでincludeすることによって全て
  # のControllerが継承する
  include SessionsHelper
end

Modelで使う時

class モデル名 < ApplicationRecord
include ActionView::Helpers
end

特定のhelperのみを使う時

class モデル名 < ApplicationRecord
include ActionView::Helpers::TutorialHelper
end

パーシャル

複数の場所から呼び出すために作成されたテンプレートのこと
パーシャルとして使うファイル名は_sample.erbのように_から始める

# renderというヘルパーの1種を使う
# 呼び出し方 読み込ませる時は「_」がいらない
# 第3引数に post: @postで変数も渡せる
<%= render "dir_name/file_name"%>

何が違うの?

パーシャルヘルパーもViewで使います。
パーシャルはhtml.erbテンプレートです
複数ページで同じレイアウトの箇所があれば、パーシャルとして切り分けることで2つの利点があります。
1. コードの記述量が少なくなり可読性が高まる
2. 再利用性が高まる

ヘルパーはviweをDRY(同じコードを繰り返さない)ためのモジュールです。
大抵は少ないコード量で、目的の実装ができるようになります。
link_toimg_tagがそれにあたります。

つまり
使いまわしたhtmlテンプレートはパーシャル
関数などのロジックはヘルパー

参考

ヘルパーとパーシャルの違いは何か
Ruby on Railsチュートリアル

2
0
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
0