【问题标题】:Missing FROM-clause, Update_all posts, where comment_ids缺少 FROM 子句,Update_all 帖子,其中 comment_ids
【发布时间】:2017-01-16 09:06:46
【问题描述】:

我想更新所有帖子,其中评论 ID

Post.includes(:comments).where(comments: {id: comment_ids}).update_all(status: 1)

错误:缺少表“cmets”的 FROM 子句条目

【问题讨论】:

  • 您是在更新帖子还是 cmets? ;)

标签: sql ruby-on-rails ruby ruby-on-rails-4 psql


【解决方案1】:

使用update_all 时,关联应加载joins 而不是includes。因为includes在另一个查询中加载了关联项,所以

Post.joins(:comments).where(comments: {id: comment_ids}).update_all(status: 1)

应该按预期工作

【讨论】:

    【解决方案2】:

    试试这个:

    posts = Post.joins(:comments).where(comments: {id: comment_ids})
    posts.update_all(status: 1)
    

    【讨论】:

      【解决方案3】:

      您还可以使用内部查询来识别需要更新的帖子。

      post_ids = Comment.where(id: comment_ids).select(:post_id) #creates query to select all posts ids
      Post.where(id: post_ids).update_all(status: 1) #executes update query on all posts
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 2015-10-30
        • 2015-11-07
        • 2020-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多