Monday, 15 April 2013

ruby on rails - undefined method `each' for nil:NilClass? -



ruby on rails - undefined method `each' for nil:NilClass? -

i want dynamically create checkboxes users in database, shall possible take (one or many). however, apparently doing wrong because code below gives me next error:

undefined method `each' nil:nilclass ... <% @users.each |user| %> <--- line 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 |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 |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 5 users in database, table isn't empty or anything. doing wrong here?

the error happens when seek submit form , fails validation. if create action renders new template, that's problem lies.

as suggested 1 of commenters, can declare @users in create action. suggest declare when fails validation (to cut down number of db queries 1 , cut down creation of unnecessary active record objects) in next code

def create @project = project.new params[:project] if @project.save redirect_to @project else @users = user.all # declare here when needed render :new end end

ruby-on-rails ruby-on-rails-3 variables view instance-variables

No comments:

Post a Comment