[英]how to get unvoted post count in Ruby on Rails
我正在使用Thumbs_up gem创建投票功能。 我有3个表-Post,User和Vote,其中Post是acts_as_voteable,而User是acts_as_voter 。
模型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 %>
有帮助吗? 提前致谢
我不确定这是否可以在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
有很多方法可以在带有NOT EXISTS的SQL中执行此条件,但是它们是非常繁琐的查询。 如果这是面对公众的行动或多次执行,那么这样做可能太重了。 我建议您对表格进行非规范化处理,并在该帖子中添加投票数。 只需使用观察者进行投票创建和删除即可更新帖子的投票计数。 然后查询将像
Post.where('votecount = 0')
该查询比上一个查询更轻松,更可扩展
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.