我有一个表posts
和一个多态表votes
。
votes
表如下所示:
create_table :votes do |t|
t.references :user # user_id
t.integer :vote # the vote value
t.references :votable # votable_type and votable_id
end
我想列出用户尚未投票的所有帖子。现在我基本上把他们已经投票的所有帖子都拿走,并从整个帖子中减去。它有效,但它现在不太方便。
def self.where_not_voted_on_by(user)
sql = "SELECT P.* FROM posts P LEFT OUTER JOIN ("
sql << where_voted_on_by(user).to_sql
sql << ") ALREADY_VOTED_FOR ON P.id = ALREADY_VOTED_FOR.id WHERE (user_id is null)"
puts sql
resultset = connection.select_all(sql)
results = []
resultset.each do |r|
results << Post.new(r)
end
results
end
def self.where_voted_on_by(user)
joins(:votes.outer).where("user_id = #{user.id}").select("posts.*, votes.user_id")
end
答案 0 :(得分:2)
好的,花了我很长时间,但答案更简单:
joins(:votes.outer, "AND user_id = #{user.id}").where("votes.vote IS NULL")