Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve undefined method `to_key' for #<Book::ActiveRecord_Relation:0x007fb709a6a8c0>?

I am facing problems with undefined method `to_key'

this is my books_controller.rb

 class BooksController  < ApplicationController
   def index
    @books = Book.where(user_id: current_user.id)
    end
 end

and my index page as follow.

index.html.erb

<div>
  <%= form_for @books do |f| %>
...
...
    <% end %>
</div>

now when I am going to access index page that time I got an error as follow.

undefined method `to_key' for #<Book::ActiveRecord_Relation:0x007fb709a6a8c0>
like image 538
Kinjal Shah Avatar asked Mar 12 '15 08:03

Kinjal Shah


1 Answers

index usually returns a collection. And indeed, your controller conforms. However, your view tries to define a form for it. This is not going to succeed, as you find out. Forms are for entities, not for collections. The bug is in your view and how you expect to handle index.

like image 143
Remus Rusanu Avatar answered Sep 20 '22 07:09

Remus Rusanu