nil的未定义方法`each':NilClass?

时间:2013-02-10 11:31:15

标签: ruby-on-rails ruby-on-rails-3 variables view instance-variables

我想动态创建数据库中用户的复选框,可以选择(一个或多个)。但是,我显然做错了,因为下面的代码给出了以下错误:

undefined method `each' for nil:NilClass
...
<% @users.each do |user| %> <--- the line with the error

控制器:

class ProjectsController < ApplicationController
    ...

    def new
      @project = Project.new
      @users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))
    end

    ...
end

视图(new.html.erb):

<%= form_for @project do |f| %>
    <div class="alert alert-block">  
        <%= f.error_messages %>
    </div>
    <div class="text_field">
        <%= f.label :title%>
        <%= f.text_field :title%>
    </div>
    <div class="text_field">
        <%= f.label :description%>
        <%= f.text_field :description%>
    </div>
    <div class="dropdown">
        <%= f.label :start_date%>
        <%= f.date_select :start_date %>
    </div>
    <div class="dropdown">
        <%= f.label :end_date%>
        <%= f.date_select :end_date %>
    </div>
    <% @users.each do |user| %>
        <%= check_box_tag "project[member_ids][]", user.id, @project.member_ids.include?(user.id), :id => "user_#{user.id}" %> 
        <%= label_tag "user_#{user.id}", user.first_name %>
    <% end %>
    <div class="checkbox">
</div>
    <div class="submit">
        <%= f.submit "Spara" %>
    </div>
<% end %>

模特:

class Project < ActiveRecord::Base
  has_and_belongs_to_many :users
  belongs_to :user
  has_many :tickets, :dependent => :destroy

  ... validations ...

  attr_accessible :user_id, :title, :description, :start_date, :end_date
end

我的数据库中有五个用户,因此该表不是空的或任何东西。我在这里做错了什么?

1 个答案:

答案 0 :(得分:7)

当您尝试提交表单并且验证失败时,会发生错误。如果您的创建操作呈现new模板,那就是您的问题所在。

根据其中一位评论者的建议,您可以在创建操作中声明@users。但我建议只在验证失败时声明它(将db查询的数量减少1并减少不必要的活动记录对象的创建),如下面的代码所示

def create
  @project = Project.new params[:project]

  if @project.save
    redirect_to @project
  else
    @users = User.all # only declare this here when it is actually needed
    render :new
  end
end