2015-03-02 26 views
0

我有軌網站紅寶石具有用戶模型和崗位模型Rails的數屬於用戶

# models/user.rb 
class User < ActiveRecord::Base 
    has_many :posts 
end 

# models/post.rb 
class Post < ActiveRecord::Base 
    belongs_to :user 
    is_impressionable 
end 

正如你可以看到所有的帖子的頁面瀏覽量,我已經使用了impressionist gem統計每個帖子的頁面瀏覽量。 要獲得特定帖子的頁面查看次數,我使用post.impressionist_count。

如何有效地獲取特定用戶所有帖子的頁面瀏覽量總和?最好將此值存儲在數據庫中,因爲我可能需要它來執行更多操作。另外,如果我將此值存儲在數據庫中,每次發佈的查看計數更改時如何更新它?提前致謝!

更新

謝謝大家對你的答案。我試圖融入您的解決方案,但我仍然無法找到解決方案。

我用counter_cache

add_column :posts, :view_count, :integer, default: 0 

# models/post.rb 
is_impressionable :counter_cache => true, :column_name => :view_count 

添加了一個列到用戶表

add_column :users, :total_view_count, :integer, default: 0 

然後做這個

# posts_controller 
before_action :update_user_total_view_count, only: :show 

private 
    def update_user_total_view_count 
     @post = Post.find(params[:id]); 
     @post.user.update_user_total_view_count 
    end 

# user model 
def update_user_total_view_count 
    update(total_view_count: posts.sum(:view_count)) 
end 

我不能使用posts.sum(:impressionist_count)因爲它不是數據庫中的列。我認爲我已經得到了這個工作,但post模型中的view_count沒有正確更新,即使impressionist_count增加,仍然停留在1。任何解決方案謝謝!

+0

該帖子是在其自己的頁面上查看的?所以它有自己的控制器動作來顯示帖子? – RichardAE 2015-03-02 13:11:41

+0

@RichardAE,是的,每個帖子都有自己的頁面。 – prajwaldp 2015-03-02 13:39:06

回答

0

我想我會在創建用戶模型的屬性:

rails g migration add_total_post_views_to_users total_post_views:integer 

然後有一個在節目中的動作(控制器)行動前:

class PostsController < ApplicationController 
    before_action :update_total_post_views, only: :show 

    def show 
    # code for displaying the post 
    end 

    private 

    def update_total_post_views 
    Post.find(params[:id]).user.update_total_post_views 
    end 

用戶模型:

class User 
    has_many :posts 

    # more code... 

    def update_total_post_views 
    update(total_post_views: posts.sum(:impressionist_count) 
    end 
+0

對接受您的答案的延遲感到抱歉。我也使用了PawełDawczak建議的counter_cache。謝謝。解決方案在更新中,但只適用於獨特的印象。爲了使其適用於所有展示次數,我在帖子模型中使用了「is_impressionable:counter_cache => true,:column_name =>:view_count,:unique =>:all」。 – prajwaldp 2015-03-14 16:06:32

0

您可能需要使用counter_cache的ActiveRecord內置機制,您正在定義將存儲緩存值的新列。有非常快的描述如何進行:

https://coderwall.com/p/tlvgag/easily-keep-track-of-rails-relationship-count-with-counter_cache

上述什麼是實現你自己的解決方案,但創業板有它的存儲緩存計數器自己的路。你有沒有嘗試過這裏描述的內容?

https://github.com/charlotte-ruby/impressionist#adding-a-counter-cache

+0

嗯...是的,我認爲你有公平的觀點 - 我首先誤解了這個問題...... – 2015-03-02 13:52:58

0

我覺得你可以做這樣的事情:

total_impressions = Rails.cache.fetch("user:#{particular_user.id}:total_impressions") do 
    Post.where(user: particular_user).reduce(0) do |sum, post| 
    sum + post.impressionist_count(:filter=>:all) 
    end 
end 

正如你可以看到這個代碼計算總的印象很重要,並將它緩存。

我不知道impressionist gem非常好,但可能有可能改進此代碼並計算DB端的總展示次數。

+0

你如何更新緩存? – 2015-03-02 13:29:49

+0

您可以1)手動使緩存失效2)設置[過期](http://apidock.com/rails/v4.1.8/ActiveSupport/Cache/Store/fetch)時間。我建議第二種方式,因爲在目前的情況下它是合適的。 – 2015-03-02 13:35:02