2013-05-10 99 views
1

我正在使用Thumbs_up創建投票功能的gem。我有3個表格 - 發佈,用戶和投票,郵政是acts_as_voteable和用戶是acts_as_voter如何在Ruby on Rails中獲取未投票的帖子數

型號Post.rb

class Post < ActiveRecord::Base 
    attr_accessible :title, :content, :user_type 
    acts_as_voteable 
    validates_presence_of :title,:content 
    default_scope order: 'posts.created_at DESC' 
end 

型號Vote.rb

class Vote < ActiveRecord::Base 
    scope :for_voter, lambda { |*args| where(["voter_id = ? AND voter_type = ?", args.first.id, args.first.class.base_class.name]) } 
    scope :for_voteable, lambda { |*args| where(["voteable_id = ? AND voteable_type = ?", args.first.id, args.first.class.base_class.name]) } 
    scope :recent, lambda { |*args| where(["created_at > ?", (args.first || 2.weeks.ago)]) } 
    scope :descending, order("created_at DESC") 
    belongs_to :voteable, :polymorphic => true 
    belongs_to :voter, :polymorphic => true 
    attr_accessible :vote, :voter, :voteable 

end 

型號User.rb

class User < ActiveRecord::Base 
    attr_accessible :name, :email, :password, :password_confirmation 
    has_secure_password 
    acts_as_voter 
    has_many :posts, dependent: :destroy 
end 

現在我想算的職位數量的,沒有投票。我試圖這樣做..

<%= Post.joins(:votes).where("dont_know_how_to_write_condition").count %> 

任何幫助?在此先感謝

+0

這是MySQL或PostgreSQL? – Lucas 2013-05-10 08:29:26

+0

在開發模式我使用的是SQLite和在生產模式下我使用postgresql – SoftwareGeek 2013-05-10 08:33:30

回答

2

我不知道這是否會在sqlite的工作輕得多,可擴展的,它應該在PostgreSQL上雖然。

def self.not_voted 
    joins("left outer join votes on votes.voteable_id = posts.id"). 
    where("votes.id is null") 
    end 

然後:

Post.not_voted.count 
+0

你是老闆:)正在工作:) :) – SoftwareGeek 2013-05-10 09:40:07

0

有一些方法可以使用NOT EXISTS在SQL中執行該條件,但它們是非常繁重的查詢。如果這種行爲是面向公衆的行爲或是多次進行的行爲,那麼這樣做可能太重了。我會建議你對錶格進行非規範化處理,並在帖子中包含一些票數。只需使用觀察員創建和刪除投票來更新帖子的投票計數。那麼查詢會像

Post.where('votecount = 0') 

該查詢比前一

相關問題