How to find out the number of records in a model?

2

I created a scaffold called a book and wanted to create a method for counting how many book entries exist in my database and use that result in the controller of another scaffold called a bulletin board where it will show the total number of books, the total loans and loans to be won

Note: Learning Rails and getting a little syntax.

    
asked by anonymous 03.06.2018 / 20:02

1 answer

0

The Active Record templates have the method #count , which can be used as follows:

Book.count
# SELECT COUNT(*) FROM books
=> 10

You can even apply conditions to the query, like this:

Book.where(status: :active).count
# SELECT COUNT(*) FROM books WHERE books.status = 1
=> 5

To use the view you can interpolate using ERB :

<p>Existem <%= Book.count %> livros disponíveis.

But it is recommended to use logics like this directly in the view, so you can use a instance variable na action:

def index
  @book_count = Book.count
end

and the view would look like:

<p>Existem <%= @book_count %> livros disponíveis.
    
07.06.2018 / 02:06