1

投票機能を作成するためにThumbs_up gem を使用しています。Post 、 User 、および Vote の 3 つのテーブルがあります。 Post はact_as_voteableで、 User はact_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

モデル投票.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

今、私はNOT VOTEDの投稿数を数えたいと思っています。私はこのようにしようとしています..

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

何か助けて?? 前もって感謝します

4

2 に答える 2

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
于 2013-05-10T08:51:12.780 に答える