Undefined local variable post

65 views Asked by At

I write this code:

<% @user.posts.each do |post| %>
    <%= render 'post', locals: { post: post, user: @user} %>
<% end %>

Then in _post.htm.erb I write follow code:

<div class="post-title">
  <img src="<%= @user.avatar.url%>" class="img-rounded post-image">
  <h4 id="post-name"><%= @user.first_name + ' ' [email protected]_name %> </h4>
  <div id="post-date"><%= post.created_at.strftime('%d %b - %k:%M') %></div>
</div>
<div class="post-content">
  <p><%= post.content %></p>
</div>
<%= render 'like', post:post %>
<li  class="post-divider"></li>

When I go to this page, I see follow:

undefined local variable or method `post'
2

There are 2 answers

1
Anuja On BEST ANSWER

You need to use partial: when you pass locals to a partial as follows:

<%= render partial: 'post', locals: { post: post, user: @user} %>

I hope this will help you.

1
K.M. On

From the PartialRenderer api.

use render partial: with locals: param or "If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials."

<%= render 'post', post: post, locals: { user: @user} %>