简体   繁体   中英

undefined method `each' for nil:NilClass?

I want to dynamically create checkboxes with the users in the database, which shall be possible to choose (one or many). However, I am apparently doing something wrong because the code below gives me the following error:

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

the controller:

class ProjectsController < ApplicationController
    ...

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

    ...
end

the view (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 %>

the model:

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

I have five users in my database, so the table isn't empty or anything. What am I doing wrong here?

The error happens when you try to submit the form and fails validation. If your create action renders the new template, that's where your problem lies.

as suggested by one of the commenters, you can declare @users in your create action. But I suggest only declare it when it fails validation (to reduce the number of db queries by 1 and to reduce the creation of unnecessary active record objects) like in the following code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM