ruby-on-rails - 如何在 ruby​​ on Rails 中获取 5 篇浏览次数最多的文章

标签 ruby-on-rails

我需要获取用户浏览次数最多的 5 篇文章。为此,我实现了“印象”功能,并且文章和印象模型之间存在多态关系。使用此功能,我无法获得每篇文章从用户那里获得的 View 。但现在我需要从数据库中获取 5 篇浏览次数最多的文章。我知道这是一个愚蠢的问题,但我尝试过但找不到答案。

schema.rb(我没有粘贴完整的文件,只是相关的)

ActiveRecord::Schema.define(:version => 20130419101017) do

  create_table "articles", :force => true do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.integer  "user_id"
  end

  create_table "comments", :force => true do |t|
    t.text     "content"
    t.integer  "user_id"
    t.string   "article_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "impressions", :force => true do |t|
    t.string   "impressionable_type"
    t.integer  "impressionable_id"
    t.integer  "user_id"
    t.string   "ip_address"
    t.datetime "created_at",          :null => false
    t.datetime "updated_at",          :null => false
  end

文章_controller.rb

class ArticlesController < ApplicationController
  before_filter :is_user_admin, only: [:new, :create, :edit, :destroy]
  before_filter :log_impression, :only=> [:show]

    def is_user_admin
      redirect_to(action: :index) unless current_user.try(:is_admin?) 
      return false 
    end

   def log_impression
     @article = Article.find(params[:id])
     # this assumes you have a current_user method in your authentication system
      @article.impressions.create(ip_address: request.remote_ip,user_id:current_user.id)
   end

      def index
          @articles = Article.all(:order => "created_at DESC")
      @article_titles = Article.first(10)
      @article_popular = Article. 
      @tags = Tag.all
      end

    def show
       @article = Article.find(params[:id])
       @related_articles = Article.joins(:taggings).
       where('articles.id != ?', @article.id)
       .where(taggings: { tag_id: @article.tag_ids }) 
    end

      def new
      @article = Article.new
      end

    def create
      @article = Article.new(params[:article])
      @article.user_id = current_user.id
      if @article.save
        flash[:success] = "article created!"
        redirect_to article_path(@article)
      else
        render 'new' 
      end 
    end

    def destroy
      @article = Article.find(params[:id])
      @article.destroy
      redirect_to action:  'index'  
    end

    def edit
      @article = Article.find(params[:id])
    end

    def update
      @article = Article.find(params[:id])
      if @article.update_attributes(params[:article])
       flash.notice = "Article '#{@article.title}' Updated!"
       redirect_to article_path(@article)
      else 
        render 'edit'
      end
    end
end

文章.rb

class Article < ActiveRecord::Base
   attr_accessible :title, :body
   attr_accessible :tag_list
   has_many :comments
   belongs_to :user
   has_many :taggings
   has_many :tags, through: :taggings
   has_many :impressions, :as=>:impressionable
   validates :title, :body, :tag_list,  :presence => true

  def impression_count
    impressions.size
  end

  def unique_impression_count
    impressions.group(:ip_address).size #UNTESTED: might not be correct syntax
  end


   def tag_list
     self.tags.collect do |tag|
      tag.name
     end.join(", ")
   end

   def tag_list=(tags_string)
     tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
     new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by_name(name) }
     self.tags = new_or_found_tags
   end
end

印象.rb

class Impression < ActiveRecord::Base
  attr_accessible :impressionable_id, :impressionable_type, :ip_address, :user_id
  belongs_to :impressionable, :polymorphic=>true 
end

文章/show.html.erb

Viewed: <%<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3ee93b2a1a7bab0bfb6fdbabea3a1b6a0a0babcbd" rel="noreferrer noopener nofollow">[email protected]</a>_count %> times

这就是我计算用户浏览量的方法。现在我想获取用户浏览次数最多的 5 篇文章。 任何帮助将不胜感激。有关更多信息,我使用 ( simple hit counter for page views in rails ) 这个来获取用户 View 。

最佳答案

我认为避免映射 ruby​​ 对象的最佳方法是使用 counter cache :

# add the impression count column to your tables
t.integer :articles, :impressions_count
t.integer :comments, :impressions_count

在您的模型中:

class Article < AR
  has_many :impressions, as: :impressionable
  has_many :comments
end

class Comment < AR
  belongs_to :article
  has_many :impressions, as: :impressionable
end

class Impression < AR
  # the counter cache here is the important option
  belongs_to :impressionable, polymorphic: true, counter_cache: :impressions_count
end

通过此设置,每次创建展示时,相应模型中的 impressions_count 列都会更新。因此,您可以简单地对展示次数进行排序,以获得前 5 个最高的展示次数:

Article.order('articles.impressions_count DESC').limit(5)

分别

Comment.order('comments.impressions_count DESC').limit(5)

当然你也可以这样做@article.impressions_count...

关于ruby-on-rails - 如何在 ruby​​ on Rails 中获取 5 篇浏览次数最多的文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16130092/

相关文章:

ruby-on-rails - 使用Rails迁移创建丢失的自动增量属性

javascript - Rails 复选框隐藏字段类

ruby-on-rails - Rspec中expect和is_expected.to的区别

ruby-on-rails - 如何使用 Rabl 读取 "order by id "JSON

ruby-on-rails - Yeoman 的角度生成器与后端(Rails 或 Sails)的集成

ruby-on-rails - Gem::InstallError: gem-wrappers 在 gem 清理期间没有安装在 GEM_HOME 中

javascript - 在 Rails i18n 中插入 javascript var

Rails 迁移过程中默认十进制值的 MySQL 错误

ruby-on-rails - habtm 关系上的计数器缓存?

mysql - Rails - 在文本列中插入超过 7786 个字符时获取 'Mysql server has gone away'