2013-10-17 44 views
0

我在我的网站上有一个博客,其中有访问过的每篇博文的博客记录。我使用这个教程作为指导来设置它。将热门博文功能添加到Ruby on Rails博客

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

什么是错误/问题? – ChrisBarthol

+0

在后控制器@popular导致视图给这个错误:** PG :: UndefinedColumn:错误:列“total_visits”不存在**我试图访问访问表来获取每个职位的__total_visits__列。 – oconn

+0

这是告诉你,你的发布表没有“total_visits”列。看看你的代码,你的“total_visits”存储在访问表中。退房http://guides.rubyonrails.org/active_record_querying.html – ChrisBarthol

回答

2

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

+0

谢谢你做到了。 – oconn