简体   繁体   English

如何在Ruby on Rails中获得未投票数

[英]how to get unvoted post count in Ruby on Rails

I am using Thumbs_up gem for creating vote function. 我正在使用Thumbs_up gem创建投票功能。 I have 3 tables - Post, User and Vote where Post is acts_as_voteable and User is acts_as_voter . 我有3个表-Post,User和Vote,其中Post是acts_as_voteable,而User是acts_as_voter

Model Post.rb 模型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

Model Vote.rb 模型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

Model User.rb 模型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

Now I want to count posts number which are NOT VOTED . 现在我要计算未投票的帖子数。 I am trying to do like this.. 我正在尝试这样做。

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

Any help?? 有帮助吗? Thanks in advance 提前致谢

I am not sure if this will work in sqlite, it should on postgresql though. 我不确定这是否可以在sqlite中工作,但是应该在postgresql上使用。

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

Then: 然后:

Post.not_voted.count

There are ways to do that condition in SQL with NOT EXISTS but they are very heavy queries. 有很多方法可以在带有NOT EXISTS的SQL中执行此条件,但是它们是非常繁琐的查询。 If this si going to be an action facing the public or performed multiple times, it might be too heavy to do it like that. 如果这是面对公众的行动或多次执行,那么这样做可能太重了。 I would recommend you to denormalize the tables and include a count of votes on the post. 我建议您对表格进行非规范化处理,并在该帖子中添加投票数。 Just use an observer on vote creation and deletion to update the vote count for the post. 只需使用观察者进行投票创建和删除即可更新帖子的投票计数。 The query then would be like 然后查询将像

Post.where('votecount = 0')

This query is much lighter and scalable than the previous one 该查询比上一个查询更轻松,更可扩展

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM