How to find the number of records of a model?

Asked

Viewed 66 times

2

I created a scaffold called a book and I wanted to create a method to count how many book entries there are in my database and use that result in the controller of another scaffold, called the bulletin board, where it will show the total of books, total loans and loans due

Note: Learning Rails and picking up a bit with the syntax.

  • 1

    already solved the problem was very simple so: inside the model of the bulletin board I put Book.Count and in the view I did <%= Book. %>

  • 1

    Correct Diego: <%= Book. %>

1 answer

0


Active Record models 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, this way:

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

To use in the view you can interpolate using the 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 in action:

def index
  @book_count = Book.count
end

and in the view would be:

<p>Existem <%= @book_count %> livros disponíveis.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.