1

This is my controller called static_pages:-

class StaticPagesController < ApplicationController #StaticPagesController is a ruby class that inherits from ApplicationController
  def home
  end

  def genre
    @genre=Genre.all

    @book=Book.find_by(genre_id:1)
  end

  def accessories
  end

  def aboutus
  end

  def contactus
  end
end
#home, genre and accessories are actions of the controller

This is a snippet of my view genre.html.erb:

<% @genre.each do|genre|%>
                <tr>
                    <td><%=genre.genre_id %></td>
                    <br>
                    <td><%=genre.genre_name %></td>
                    <br>
                    <td><%=genre.description %></td>
                    <br>
                    <br>
                </tr>
<% end %>

<% @book.each do|book|%>
                <tr>
                    <td><%=book.book_name %></td>
                    <br>
                    <td><%=book.pages %></td>
                    <br>
                    <td><%=book.stock %></td>
                    <br>
                    <td><%=book.synopsis %></td>
                    <br>
                    <td><%=book.mrp%></td>
                    <br>
                    <td><%=book.author %></td>
                    <br>
                    <td><%=book.publisher %></td>
                    <br>
                    <td><%=book.rating %></td>
                    <br>
                    <td><%=book.genre_name%></td>
                    <br>
                    <td><%=book.discount %></td>
                    <br>
                    <br>
                </tr>
<% end %>

I'm getting an error for the book portion when I open the genre view. It says that undefined method `each' for #Book:0x007f014ab326d8. I'm not sure why I'm getting this error because I copy pasted the thing from the genre part and that's not showing an error so why is this?

Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37
sindhugauri
  • 189
  • 2
  • 14
  • 1
    Possible duplicate of [find vs find\_by vs where](http://stackoverflow.com/questions/11161663/find-vs-find-by-vs-where) – Vucko Apr 26 '17 at 12:52
  • `@book=Book.find_by` returns a single instance, you can cycle thru that with `each` – Eyeslandic Apr 26 '17 at 12:53

2 Answers2

1
 def genre
   @genre=Genre.all
   @books =Book.where(genre_id:1)
 end

here Book.where will return as collection

Dnyanarth lonkar
  • 869
  • 7
  • 12
0

As per the documentation in here

find_by-

The find_by method finds the first record matching some conditions. For example:

So essentially it will limit the result of the query to only 1 record, and each method works on collection of records

SELECT "books".* FROM "books" WHERE "books"."genre_id" = $1 LIMIT 1[["genre_id", 1]]

If I use where Book.where(genre_id:1)

The query fired is SELECT "books".* FROM "books" WHERE "books"."genre_id" = $1 [["genre_id", 1]]