2

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

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

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

4

1 回答 1

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
于 2013-02-10T13:06:16.410 回答