2

我想动态创建与数据库中的用户复选框,这应该可以选择(一个或多个)。不过,我显然是做错了什么,因为下面的代码给我下面的错误:未定义的方法`each'for nil:NilClass?

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 

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

+0

我会建议包括'@users建议只把它声明= ...'语句也在你的控制器的'create'动作中。 – 2013-02-10 12:02:37

回答

7

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

按照其中一位评论者的建议,您可以在创建操作中声明@users。但是,我当它验证失败(由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 
+0

与rails 4.2有类似的问题,这个答案帮助我解决了这个问题。 – Lotix 2016-02-06 22:23:05

相关问题