我的应用程序具有简单的用户/帖子/投票结构,用户可以对每个帖子进行投票/投票。我想让用户在索引页面上看到“他们自己的未投票帖子”,我尝试where
where.not
但无法将其合并到工作中。
我尝试在posts_controller
中执行此操作,我最好的尝试是查找所有未投票的帖子,但不知道如何与用户相关。
def index
if logged_in?
@posts = Post.where.not(id: Vote.all.map(&:voteable_id))
else
@posts = Post.all.sort_by{|x| x.total_votes}.reverse
end
结束
投票是多态关联,下面是3个模型:
Post: has_many :votes, as: :voteable,
Vote: belongs_to :voteable, polymorphic: true,
User: has_many :votes
我logged_in?
判断@current_user
是否存在。
答案 0 :(得分:1)
我不确定“他们自己的未投票帖子”是什么意思,因为你的示例代码有点令人困惑。
如果您需要找到当前用户没有投票的帖子,您应该执行以下操作:
current_user.posts.where.not(id: Vote.pluck(:voteable_id).uniq)
另一方面,如果你需要找到当前用户尚未投票的帖子,你应该只使用当前用户的投票:
Post.where.not(id: current_user.votes.pluck(:voteable_id).uniq)
希望有所帮助
提示:如果您需要提高代码效率,可以使用左连接而不是搜索除了之外的ID来使其在一个查询中运行。