Form with list below - List shows blank entry

51 views Asked by At

I have a controller:

class UsersController < ApplicationController

 def departments
    @users_departments = current_user.departments
    @new_department = current_user.department.new
 end

My view looks similar like this:

 <%= form_for @new_department, :url => {:action => "departments"} do |f| %>
.
<% end %>

<% @users_departments.each do |dept| %>
  <td><%= dept.name %></td>
  <td><%= dept.employees %></td>
<% end %>

@users_departments.each... shows me an empty department. Why? And how to solve that?

2

There are 2 answers

0
Jan On

Ok I found out that the magic thing is called lazy and eager loading.

What I made was changing this:

@users_departments = current_user.departments

to

@users_departments = current_user.departments.find(:all)

Rails seems to be loading the results in the view if it was called. With "find" in place the db get hit and @users_departments fetches "really" the entries. Not in view, like before.

1
Dmytro Vasin On

First of all - try to use REST form_for doc

something like that:

<%= form_for @post do |f| %>

will generate link to create action in your UserController

And about @users_departments.each - maybe in your DB current_user.departments.count - return 0

I mean maybe there is no such record in your database.