如何在rails中调试NoMethodError

时间:2015-04-04 12:29:39

标签: ruby-on-rails

我正在关注jumpstartlabs blogger tutorial,我接下来的第i5节并努力在作者中获得NoMethodError#new

这是堆栈跟踪:

NoMethodError in Authors#new
Showing /home/.../blogger/app/views/authors/_form.html.erb where line #16 raised:

undefined method `username' for #<Author:0xb6379068>
Extracted source (around line #16):

  <div class="field">
      <%= f.label :username %><br>
      <%= f.text_field :username %>
  </div>
  <div class="field">
    <%= f.label :email %><br>

Trace of template inclusion: app/views/authors/new.html.erb

new.html.erb非常简单

<h1>New Author</h1>

<%= render 'form' %>

<%= link_to 'Back', authors_path %>

这是我的_form.html.erb

<%= form_for(@author) do |f| %>
  <% if @author.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@author.errors.count, "error") %> prohibited this author from being saved:</h2>

      <ul>
      <% @author.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
      <%= f.label :username %><br>
      <%= f.text_field :username %>
  </div>
  <div class="field">
    <%= f.label :email %><br>
    <%= f.text_field :email %>
  </div>
<div class="field">
  <%= f.label :password %><br />
  <%= f.password_field :password %>
</div>
<div class="field">
  <%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %>
</div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我真的想知道我可以在rails控制台中做些什么来调试它。或者如何阅读跟踪以找出发生这种情况的原因。如果需要,我可以附加更多的完整跟踪,但它很长。

1 个答案:

答案 0 :(得分:1)

rails错误消息足够清晰。它表示Author类的实例不响应username。确保您已正确定义数据模型并提供所有数据库迁移(您必须在authors表中具有用户名字段)。运行rails console(rails c)并尝试Author.new.username进行检查,或Author.new.attributes列出已定义的属性。