【问题标题】:Active Record Query in railsRails 中的活动记录查询
【发布时间】:2017-06-11 18:10:42
【问题描述】:

我想查找与多个评论相关联的所有博客文章。如何在 rails 控制台中使用 ActiveRecord 查询来执行此操作?

blog_post has_many :cmets

 blog = Blog.all
 blog.find(:comments > 1)

【问题讨论】:

  • 你必须先尝试一些东西,然后发布你尝试过的东西。

标签: ruby-on-rails activerecord


【解决方案1】:

您的问题定义有点模糊,但我仍然尝试回答。

最简单的方法可能是在BlogPost 模型中为您的 cmets 设置计数器缓存。如果您在一篇博文中有很多 cmets,此解决方案也可以更好地扩展。

例如:

class BlogPost < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :blog_post, dependent: :destroy, counter_cache: true
end

然后只需添加一个迁移,将 comments_count 添加到博客文章表中,Rails 会处理其他所有事情。

class AddCommentsCountToBlogPosts < ActiveRecord::Migration[5.0]
  def change
    add_column :blog_posts, :comments_count, :integer
  end
end

现在你可以这样做了:

posts_with_comments = BlogPost.where('comments_count >= ?', 1)

【讨论】:

    【解决方案2】:
    blog_ids_with_comments = Blog.select(:id).
      joins(:comments).
      groupBy('blogs.id').
      having('count(comments.id) > 1')
    
    blogs = Blog.find blog_ids_with_comments
    

    您必须将此 SQL 转换为 ActiveRecord 查询:

    select blogs.id from blogs join comments on blog.id = blog_id
      group by blogs.id having count(comments.id) > 1;
    

    如果您选择所有Blog 字段并按所有Blog 字段分组,您实际上可以将其减少到一行。 Rails 可能有一个快捷方式来指定记录的所有字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多