1
4

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.

【Rails】パーシャルまとめ

Last updated at Posted at 2020-02-13

パーシャルを使う目的

viewの一部を別ファイルに切り出し、可読性と再利用性を上げる。

基本の使い方

・パーシャルファイルの名前は_から始まる(_graph.html.erbなど)
・パーシャルが同じディレクトリにある時はrender '{ファイル名}'で呼びだす。(拡張子不要)

<%= render 'graph' %>

・違うディレクトリの時はrender '{ディレクトリ名/ファイル名}'で呼びだす。

<%= render 'shared/error_messages' %>

変数を渡す

<%= render partial: 'graph', locals: { id: 1, name: '棒グラフ'} %>
または
<%= render 'graph', id: 1, name: '棒グラフ' %>
_graph.html.erb
ID:<%= id %>
名前:<%= name %>

collectionオプション(応用)

collectionオプションに複数形のインスタンス変数を渡すと、渡されたインスタンスの要素分そのテンプレートを繰り返し表示します。

<%= render partial: 'book_detail', collection: @books, as: 'book' %>

この場合、
@booksに格納されているインスタンス分だけ_book_detail.html.erbが繰り返し表示されます。
・呼び出されたパーシャル内ではbookという名前のインスタンスを利用することができます。
book_counterという名前のindexの変数が自動で作られます。(0から始まる)

Railsのpartialでcollectionを渡すときにはindexの変数が自動的に作られる

参考

【Rails基礎】ややこしい部分テンプレートの省略形について簡単にまとめてみた
【Rails】部分テンプレートの使い方を徹底解説!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?