未定义的方法`电子邮件'为nil:NilClass

时间:2012-04-28 03:58:11

标签: ruby-on-rails

我在以下某个观点中遇到以下代码的问题:

<% if !@admin.emails.nil? %>
<% @admin.emails.each do |email| %>
  <tr>
    <td><%= email.email %></td>
  </tr>
<% end %>
<% end %>

这会产生错误:

undefined method `emails' for nil:NilClass
Extracted source (around line #1):
1: <% @admin.emails.each do |email| %>
2:   <tr>
3:     <td><%= email.email %></td>
4:   </tr>

管理员控制器:

class AdminController < ApplicationController
end
def index
      @emails = Email.all
      respond_to do |format|
       format.html # index.html.erb
       format.xml  { render :xml => @emails }
     end
end

电子邮件模型:

class Email < ActiveRecord::Base
  attr_accessible :email
  belongs_to :admin
  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :email, :presence   => true,
                    :length     => { :maximum => 250 },
                    :format     => { :with => email_regex },
                    :uniqueness => { :case_sensitive => false }

end

管理模式:

class Admin < ActiveRecord::Base
  has_many :emails
end

知道可能出现什么问题吗?

1 个答案:

答案 0 :(得分:1)

您的索引方法不在AdminController中......:)

它定义@emails而不是@admin