Class User
has_many :posts
end
Class Post
belongs_to :users
end
我有一个帖子的内容,想知道是否有用户发送过具有相同内容的帖子。如果我只针对单个用户进行搜索,我可以很容易地找到它。
user.posts.exists?(content: params[:content])
我想查看数据库中的所有用户。
users = Users.all
users.posts # will not work NoMethodError: undefined method `posts' for #<Array:0x007fbe818fbd98>
如果有一个匹配项,我需要一个true
,如果没有用户具有匹配的内容,我需要一个false
,对于所有发布的帖子用户。
我总是可以在一个 block 中循环它并以这种方式获得结果,有没有一种方法可以在一行代码中做到这一点?
最佳答案
尝试这样的事情:
posts = Post.where(content: params[:content])
users = User.find posts.map(&:user_id)
或者更短的:
users = User.find Post.where(content: params[:content]).pluck(:id)
或者如果您只需要检查是否存在具有给定内容的帖子(由任何用户创建):
Post.exists?(content: params[:content])
关于ruby-on-rails - Ruby 查找具有特定帖子内容的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33805902/