在我的一种观点中,我对以下代码有疑问:
<% 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
知道有什么问题吗?