Joseph Lee
Joseph Lee

Reputation: 47

error_message partial getting a NameError: undefined local variable or method `object'

I've researched this error but I'm not able to resolve this issue.

Here is _micropost_form.html.erb:

<%= form_for @micropost do |f| %>
  <%= render partial: 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_field :content, placeholder: " Caption..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
  <span class="picture">
    <%= f.file_field :picture %>
  </span>
<% end %>

Here is _error_messages.html.erb

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

Here is microposts_controller

def new
  @micropost = current_user.microposts.build
  @feed_items = current_user.feed.paginate(page: params[:page])
end

Upvotes: 1

Views: 434

Answers (3)

akbarbin
akbarbin

Reputation: 5105

You can change your code below

<%= render partial: 'shared/error_messages', object: f.object %>

into

<%= render partial: 'shared/error_messages', object: f.object %>

I hope this help you.

Upvotes: -3

gwalshington
gwalshington

Reputation: 1505

A couple thoughts:

Does f.object have a value?

Also - try something like this for passing object to the partial:

<%= render partial: 'shared/error_messages', :locals => {:object => f.object} %>

Upvotes: 0

Pavan
Pavan

Reputation: 33552

NameError: undefined local variable or method `object'

You can render a partial in two ways, render and render partial:. But when you are using partial:, you need to send the variables in the locals: hash. So this won't work

<%= render partial: 'shared/error_messages', object: f.object %>

It should be

<%= render partial: 'shared/error_messages', locals: {object: f.object} %>

Or without the partial: key

<%= render 'shared/error_messages', object: f.object %>

Upvotes: 0

Related Questions