LoginSignup
31
21

More than 3 years have passed since last update.

【Rails】パーシャルを利用する

Posted at

Railsではviewファイルで使う部品(パーシャル)を作り、他のviewファイルから呼び出して利用することができます。

パーシャルの基本ルール

・ファイル名はアンダースコアから始まる
render '{ファイル名}'で呼びだす
・パーシャルが同じディレクトリにある時はrender '{ファイル名}'、違うディレクトリの時はrender '{ディレクトリ名/ファイル名}'で呼びだす。(拡張子不要)

使ってみる

簡単なTODOアプリのエラーメッセージをパーシャル化して利用します。
Ruby on Railsで簡単なアプリを作成
TODOアプリにバリデーションを追加する

パーシャルを作成

/app/views/shared/_error_messages.html.erb
<% if @task.errors.any? %>
  <div>
    <ul style="color: red">
      <% @task.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
    </ul>
  </div>
<% end %>

パーシャルを呼び出す

/app/views/new.html.erb
<h1>新規タスク</h1>
<%= render 'shared/error_messages' %>
<%= form_for(@task) do |f| %>
  <div><%= f.label :title %></div>
  <div><%= f.text_field :title %></div>
  <div><%= f.submit %></div>
<% end %>
<%= link_to '戻る', tasks_path %>
/app/views/edit.html.erb
<h1>タスク編集</h1>
<%= render 'shared/error_messages' %>
<%= form_for(@task) do |f| %>
  <div><%= f.label :title %></div>
  <div><%= f.text_field :title %></div>
  <div><%= f.submit %></div>
<% end %>
<%= link_to '戻る', tasks_path %>
31
21
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
31
21