Count the Number of Entries in an Ecto Repository

Andrew Hendrie picture Andrew Hendrie · Apr 18, 2016 · Viewed 11.9k times · Source

Whats the quickest way to see the number of entries in my database? I'd like to see the number of posts in my posts/index view.

Say I have a Post model and a bunch of posts saved in my database. In Rails I could do something like this in a view file:

<h1><%= @posts.length %> Posts</h1>

or

<h1><%= @posts.size %> Posts</h1>

or

<h1><%= @posts.count %> Posts</h1>

What's the Phoenix Framework/Elixir equivalent?

Answer

Gazler picture Gazler · Apr 18, 2016

The options that Dogbert has provided are both correct and should be used for Ecto 1.x.

In Ecto 2.0 you can use Repo.aggregate/4

Repo.aggregate(Post, :count, :id)