[英]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.