Reputation: 577
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>
Upvotes: 9
Views: 21347
Reputation: 932
Should be:
class BooksController < ApplicationController
def index
@book = Book.find_by_id(2)
end
or
def index
@book = Book.new
end
Upvotes: 11
Reputation: 294207
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
.
Upvotes: 18