hugalves
hugalves

Reputation: 373

Why simple_form raises "undefined method `model_name' for NilClass:Class"?

I'm studying how to use simple_form gem at index.html.erb from my user's folder. I have no success. The weird thing is that it is working at _form.html.erb. Why?

users_controller.rb

def index
   @users = User.find_by_sql(["SELECT id, name, login, password
                               FROM users"])
end

users/index.html.erb
<%= simple_form_for @users do |f| %>
  <p>
    <%= f.input :name %>
  </p>
  .
  .
  .
  <p>
    <%= f.button :submit %>
  </p>
<% end %

It is raising this exception: undefined method `model_name' for NilClass:Class

Any ideas?

Upvotes: 2

Views: 3369

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

You are trying to create a form for an array of users, but simple_form_for takes a single record, not an array. If what you want is a list of forms, one for each user, then this would do that:

users/index.html.erb

<% @users.each do |user| %>
  <%= simple_form_for user do |f| %>
    <p>
      <%= f.input :name %>
    </p>
    <p>
      <%= f.button :submit %>
    </p>
  <% end %>
<% end %>

But this seems like a strange thing to do, shouldn't this form be on your new page, and not the index page?

Alternatively, if you want to have a form for a user alongside a list of users on your index page, you would need to create that user in your index action:

def index
  @users = User.find_by_sql(["SELECT id, name, login, password
                           FROM users"])
  @user = User.new
end

Then you can create the form with simple_form_for @user do |f| ... in the view, and also access the list of users with @users.

Upvotes: 3

Related Questions