2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Perfect answer and explanation shioyama!! I didn't know about single record! I used on index.html.erb just for studying! Thank you!
Glad to have been of help. By the way, if you just want to fetch all users in the database, you can just use User.all (easier than find_by_sql).
Sure. Actually, I used find_by_sql because I want to retrieve just some fields from Users table. Can I fetch them using User.all?
Oh sorry, yes you can: User.find(:all, :select => 'id, name, login, password'). Generally it's better not to insert explicit SQL if you can help it, so that your code will work on any DB.
Nice!! I will this one! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.