【问题标题】:Multiple where clauses in Ruby Rails [closed]Ruby Rails 中的多个 where 子句 [关闭]
【发布时间】:2020-10-30 07:21:01
【问题描述】:

我正在尝试在 Rails 中创建一个搜索功能,允许用户使用在其标题、“材料列表”或标签列表中找到的关键字来搜索帖子。

按标题搜索既简单又直接。添加搜索“材料”关联表的功能需要研究,但我能够想出:

tags = Tag.where("tag_name LIKE ?","%"+params[:q]+"%").pluck("tag_id")

@searchResults = Post.joins(:materials).where("post.name OR materials.name  LIKE ?", "%"+ params[:q]+"%")

但是,现在我想将标签表添加到搜索中。当我尝试以下方法时,我收到 PreparedStatementInvalid 错误:

tags = Tag.where("tag_name LIKE ?","%"+params[:q]+"%").pluck("tag_id")

@searchResults = Post.joins(:materials, :post_tags, :tags).where("post.name OR materials.name  LIKE ? OR tags.include?(post_tags.tag_id)", "%"+ params[:q]+"%")

我有一个包含标签名称和标签 ID 列表的表格,以及一个包含没有标签名称的帖子/标签对列表的表格。所以我需要能够进行查询,搜索标签列表,获取 id,然后使用它从 post_tags 表中查找帖子并在搜索中返回。

另一种方法:

tags = Tag.where("tag_name LIKE ?","%"+params[:q]+"%").pluck("tag_id")

@searchResults = Post.joins(:materials, :post_tags, :tags).where("post.name OR materials.name  LIKE ? ", "%"+ params[:q]+"%").or(where(tags.include?(post_tags.tag_id))

【问题讨论】:

  • SQL 域中没有tags.include?(post_tags.tag_id)
  • 注意:Ruby 是一种区分大小写的语言,大写字母在语法方面具有特定的含义。变量和方法名称应该是小写字母。大写字母表示ClassNameCONSTANT_NAME 形式的常量。
  • 这是 MySQL 还是 Postgres? Postgres 具有可以索引的数组列,这对于这种情况非常有用。 MySQL 更喜欢关系型表结构。
  • 您可能还对github.com/mbleigh/acts-as-taggable-on感兴趣
  • @max 对于关联来说,这不是一个好的选择,我完全同意这一点,但对于像“标签”这样简单且非参考的东西,它的效果非常好。

标签: ruby-on-rails ruby where-clause


【解决方案1】:

未经测试,但也许这样的东西会起作用:

q_for_like = "%"+params[:q]+"%"

post_ids = PostTag.joins(:tag).where("tags.tag_name LIKE ?", q_for_like).pluck("post_id")

@searchResults = Post.
    joins(:materials).
    where(
        "post.id IN(?) OR post.name LIKE ? OR materials.name LIKE ?",
        post_ids, q_for_like, q_for_like
    )

我假设 "post.name OR materials.name LIKE ?" 没有按您原来示例中的预期工作,所以如果我错了,请更改它。

编辑:另外,也许 post.id 和 post.name 应该是 posts.id 和 posts.name 。

【讨论】:

  • 谢谢。这对我来说不是解决方案,但有所帮助。 PostTag 属于 Tag,所以我需要从 Tag 获取 tag_names 的列表,然后使用这些结果和 IN(?) 从 PostTag 获取 post_ids 的列表,然后创建以下搜索结果:Post.joins(:materials).where("posts.name LIKE ? OR materials.name LIKE ? OR posts.id IN(?)", q_for_like, q_for_like, post_ids). However now this repeats results multiple times for as many "materials" there are for each post.
  • 另外,post.name OR materials.name LIKE ? 确实为我工作
  • 我对@9​​87654331@ 的期待是LIKE 部分仅应用于materials.name 而不是post.name;只要帖子有名称(任何名称),post.name 就会为真。对于重复,也许看看distinct
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2022-11-16
  • 1970-01-01
相关资源
最近更新 更多