【问题标题】:How to query an ActiveRecord table using conditions based on another table?如何使用基于另一个表的条件查询 ActiveRecord 表?
【发布时间】:2015-01-30 22:33:33
【问题描述】:

我有两个模型 - Blog 和 BlogTag。博客 has_many :blog_tags 和 BlogTag belongs_to :blog:

blog.rb

has_many :blog_tags

blog_Tag.rb

belongs_to :blog

我想查询数据库以根据用户在表单字段中输入的内容选择所有在 blog_tags 表中具有匹配标签的博客。像这样的:

Blog.where(blog_tags contain [array of tags])

有没有办法用 ActiveRecord 做到这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    假设 BlogTag 有一个列 name

    Blog.joins(:blog_tags).where(blog_tags: { name: [array of tags] }).uniq
    

    这仍然会返回博客,但只会返回名称在数组中的博客标签的博客。

    【讨论】:

    • 如果博客有来自该数组的多个标签...(在答案中暗示潜在的陷阱)
    • 是的,它会返回多个...可能需要一个 uniq
    【解决方案2】:

    另一种方法是将BlogTag 关系传递到Blog 范围。

    Blog.where(id: BlogTag.where(name: tags).select(:blog_id))
    

    因此,ActiveRecord 将构造一个子查询,而不是 JOIN

    SELECT * FROM blogs WHERE id IN (
      SELECT blog_id FROM blog_tags WHERE name IN ('tag1', 'tag2', 'tag3')
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多