1

I'm following the ruby on rails tutorial. And I received a error on my signup page only.

undefined local variable or method `object' for #<#<Class:0x007feb442f6a98>:0x007feb442f8438>

Extracted source (around line #1):

1: <% if object.errors.any? %>
2:  <div id="error_explanation">
3:      <h2>
4:          <%= pluralize(object.errors.count, "error") %>

Here's my error_messages file.

<% if object.errors.any? %>
    <div id="error_explanation">
        <h2>
            <%= pluralize(object.errors.count, "error") %>
            prohibited this <%= object.class.to_s.underscore.humanize.downcase %> from being saved:
            </h2>
            <p>There were problems with the following fields:</p>
            <ul>
            <% object.errors.full_messages.each do |message| %>
            <li><%= message %></li>
            <% end %>
            </ul>
    </div>

    <% end %>

Now here's my users/new.html file.

<h1>Sign up</h1>

<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= render 'fields', :f => f %>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
4

1 回答 1

0

The object passed down with :object => becomes a local variable in the partial with the same name as the partial. So in this case, where your partial is called error_messages, the first line should be

<% if error_messages.errors.any %>

Now obviously this looks a little confusing - which is perhaps a suggestion the naming of the partial is wrong.

Also, partial view files should be named starting with an underscore - shared/_error_messages - to mark they're not full views; they should be rendered with render :partial => 'shared/error_messages'; and the :object local variable doesn't carry the underscore.

See some docs on rendering partials.

于 2013-02-05T17:13:38.450 回答