A
A
Anton Ipatov2019-01-17 14:21:07
Ruby on Rails
Anton Ipatov, 2019-01-17 14:21:07

How to count the number of visits in Ruby?

The post.rb model belongs to source.rb
Post.rb has a number of visits (visits)
How to count the number of visits for a particular source?

class Post
  include Mongoid::Document

  field :visits, type: Integer

  belongs_to :source, touch: true, index: true
end

Now it's done like this, maybe there is a better way?
source.rb
class Source
  include Mongoid::Document
  has_many :posts, dependent: :destroy

  def total_amount
    posts.sum(:visits)
  end
end

<% @sources.each do |source| %>
  <%= source.total_amount %>
<% end %>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question