将流行的帖子功能添加到Ruby on Rails博客

时间:2013-10-17 04:15:49

标签: ruby-on-rails ruby ruby-on-rails-4 erb

我的网站上有一个博客,每个访问过的帖子都有一个vist计数。我使用本教程作为设置指南。

Railsthink.com

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

schema.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

visit.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

visit_detail.rb

    class VisitDetail < ActiveRecord::Base
      belongs_to :visit
    end

以下是我尝试通过执行此类操作添加功能的地方,但这不会访问“访问”表

posts_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>

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

1 个答案:

答案 0 :(得分:2)

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