0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails初学者】部分テンプレートでundefined local variable or method 'article'エラーが出た原因と解決方法

Posted at

【Rails】エラーで、部分テンプレートでundefined local variable or method 'article'が出た原因と解決方法

こんにちは。
現役の看護師で、エンジニア転職を目指している者です。
Railsでブログアプリを作っていたとき、以下のようなエラーに遭遇しました。

NameError in Articles#index
Showing app/views/articles/_article.html.erb where line #1 raised:

undefined local variable or method `article' for an instance of #<Class:0x...>

_article.html.erbの先頭で定義されている変数articleが使えない、というエラーです。

問題のコード

まず、エラーが出ていた時点のコードはこちらでした。

app/views/articles/index.html.erb

<div class="container">
  <%= render 'tabs' %>

  <% @articles.each do |article| %>
    <%= render 'article' %>
  <% end %>

  <%= link_to new_article_path do %>
    <div class="float_btn">
       <i class="fa fa-plus"></i>
    </div>
  <% end %>
</div>

app/views/articles/_article.html.erb

<%= link_to article_path(article) do %>
  <div class="card">
    <div class="card_image">
      <%= image_tag 'eyecatch1.png' %>
    </div>
    <div class="card_content">
      <div class="card_title">
        <%= article.title %>
      </div>
      <div class="card_heart">
        <%= image_tag 'heart.svg' %>
        <span>23</span>
      </div>
      <div class="card_detail">
        <%= image_tag 'default-avatar.png' %>
        <div>
          <p>chibacity</p>
          <p><%= article.display_created_at %></p>
        </div>
      </div>
    </div>
  </div>
<% end %>

エラーの原因

render 'article'と書いただけでは、_article.html.erbarticleというローカル変数が渡されないらしいです。
Railsで部分テンプレートに変数を渡したい場合は、ローカル変数として明示的に渡す必要があります。

解決方法

以下のように修正しました

<% @articles.each do |article| %>
  <%= render 'article', article: article %>
<% end %>

このように書くことで、 _article.html.erb内でarticleというローカル変数が使えるようになります。

学び

  • render 'partial_name'だけではローカル変数は渡らない
  • undefined local variable or methodが出たら、まずローカル変数の渡し忘れを疑う
  • Railsを触り始めたばかりだと見落としてしまいがちの、部分テンプレートの基本的な使い方を身につけると、ビューがずっと読みやすくなりそうです。

引き続き、学習を進めます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?