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

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

我已经研究过这个错误,但我无法解决这个问题。

这里是_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 %>

这里是_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 %>

这里是microposts_controller

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

您可以在下面更改您的代码

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

进入

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

希望对你有所帮助。

几个想法:

f.object有值吗?

此外 - 尝试像这样将 object 传递给部分:

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

NameError: undefined local variable or method `object'

您可以通过 renderrender partial: 两种方式呈现 局部 。但是当您使用 partial: 时,您需要在 locals: 散列中发送 变量 。所以这行不通

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

应该是

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

或者没有 partial:

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