【问题标题】:Rails 4, ActiveRecord, find all posts that are not commented by current userRails 4,ActiveRecord,查找当前用户未评论的所有帖子
【发布时间】:2016-03-12 00:40:15
【问题描述】:

正如标题所暗示的那样,寻找正确的 ActiveRecord 语法来查找 Devise current_user 尚未在其中发表评论的所有帖子...我尝试搜索类似内容,但找不到任何内容。请注意微妙的请求 - 我不是在寻找所有没有 cmets 的帖子,而是在寻找 current_user 没有发表评论的所有帖子。希望有人能帮忙!

Post has_many Comments,Comment belongs_to Post。

提前致谢!

【问题讨论】:

  • 其他人有什么想法吗?想看看其他选择。谢谢!

标签: ruby-on-rails-4 activerecord devise find where


【解决方案1】:

您有关于用户评论了哪些帖子的信息,因此您基本上只需搜索“其他”帖子。

class User
  has_many :comments
end

class Post
  has_many :comments

  scope :not_commented_by, ->(user) { 
    where.not(id: user.comments.select('post_id as id'))
  }
end

# in a controller
def index
  @posts = Post.not_commented_by(current_user)
end

【讨论】:

  • 在 Post 模型中出现语法错误 - 在(用户)处 ->
  • 嗯仍然看到错误。它突出显示 -> 和 { 之间的空间
  • 已修复。再试一次。抱歉,我来晚了。
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2011-04-29
  • 2023-04-10
相关资源
最近更新 更多