2013-05-10 95 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') 

该查询比前一

相关问题