0

我的网站上有一个博客,其中包含访问的每个帖子的访问次数。我使用本教程作为设置它的指南。

Railsthink.com

按照教程,我能够设置它。现在我想添加一个使用计数来列出帖子/索引页面上的热门帖子的功能。

架构.rb

    create_table "posts", force: true do |t|
      t.string   "title"
      t.text     "text"
      t.datetime "created_at"
      t.datetime "updated_at"
      t.text     "description"
      t.string   "cover_image_file_name"
      t.string   "cover_image_content_type"
      t.integer  "cover_image_file_size"
      t.datetime "cover_image_updated_at"
      t.string   "slug"
    end

    add_index "posts", ["slug"], name: "index_posts_on_slug", unique: true, using: :btree

    create_table "visit_details", force: true do |t|
      t.integer  "visit_id"
      t.string   "ip_address", limit: 15
      t.datetime "created_at"
      t.datetime "updated_at"
    end

    add_index "visit_details", ["ip_address"], name: "index_visit_details_on_ip_address", using: :btree
    add_index "visit_details", ["visit_id"], name: "index_visit_details_on_visit_id", using: :btree

    create_table "visits", force: true do |t|
      t.integer  "visitable_id"
      t.string   "visitable_type", limit: 30
      t.integer  "total_visits"
      t.integer  "unique_visits"
      t.datetime "created_at"
      t.datetime "updated_at"
    end

    add_index "visits", ["visitable_id"], name: "index_visits_on_visitable_id", using: :btree
    add_index "visits", ["visitable_type"], name: "index_visits_on_visitable_type", using: :btree

post.rb

    class Post < ActiveRecord::Base
      has_one :visit, :as => :visitable
    end

访问.rb

    class Visit < ActiveRecord::Base
      belongs_to :visitable, :polymorphic => true
      has_many :visit_details

      def self.track(obj, ip_address)
        visit = Visit.find_or_create_by_visitable_id_and_visitable_type(obj.id, obj.class.name)
        ### check if visit is unique
        unless VisitDetail.find_by_visit_id_and_ip_address(visit.id, ip_address)
          visit.increment!(:unique_visits)
        end
        visit.increment!(:total_visits)
        visit_detail = visit.visit_details.create(:ip_address => ip_address)
      end
    end

访问详细信息.rb

    class VisitDetail < ActiveRecord::Base
      belongs_to :visit
    end

这是我试图通过执行类似操作来添加功能的地方,但这不会访问访问表

post_controller.rb

    class PostsController < ApplicationController
      index def
        @popular = Post.order('total_visits DESC').limit(5)
      end
    end

然后在我看来,我想尝试这样的事情

帖子/index.html.erb

    <div>
      <h3>Popular Posts:</h3>
      <ul>
        <% @popular.each do |post| %>
          <li><%= post.name %></li>
        <% end %>
      </ul>
    </div>

感谢您抽出宝贵时间提供帮助。

4

1 回答 1

2

尝试Post.joins(:visit).order('total_visits DESC').limit(5)

于 2013-10-17T05:01:18.620 回答