Neat little view count trick (capture views per date) - damn Elixir is cool!

I want to capture views per date, and create or increase the count on each hit. Elixir and Ecto makes this super easy and cool. Damn!

def track_view(book) do
  Repo.insert(%View{book_id: book.id, date: Date.utc_today(), total_views: 1},
    conflict_target: [:book_id, :date],
    on_conflict: [inc: [total_views: 1]]
  )
end
13 Likes

Worth to mention, that you need a unique_index on [:book_id, :date] for it to work.

But yeah, upserts are cool.

4 Likes