ruby-on-railssimple-formsimple-form-for

Error while trying to use simple_form following a table


Rails 6
simple_form
bootstrap 4

I have a table, in my views/books/index.htmlslim, that I would like to add a simple_form to, as follows:

table.table.table-striped
  thead
    tr
      th Name
  tbody
    - @books.each do |book|
      tr
        td = book.name

= simple_form_for(@book) do |f|
  .form-inputs
    = f.input :book_name

  .form-actions
    = f.button :submit

I am, however, getting an error message, telling me:

ActionView::Template::Error (undefined method `model_name' for nil:NilClass):

Assuming because this is the Index view. How do I fix this?

Edit:

To clarify, when I submit the form, I want it to go to the book new controller action, not the index action, so I am looking for the equivalent of:

= form_with url: new_book_url do |f|

Solution

  • You need to set @book instance variable in your index action:

    def index
      @book = Book.new
      # rest of the code, setting @books etc.
    end