包含在 where 条件中

Contains in a where condition

技术规格:ruby 2.2.1p85,Rails 4.2.3.

这是完美的工作:

@performances = Performance.where(date: start_date..end_date).includes(:production_page).where(pages: {organization_id: organization_id, layout_id: nil, genre: genre_word})

我的问题是目前,流派和 genre_word 需要完全匹配。我需要知道 genre 是否包含 genre_word。我试过包括? (语法错误)并尝试使用 .find_by_sql.

重写查询

示例:

genre_word: Comedy

pages.genre: Comedy, Drama 

理想情况下,pages.genre 和 genre_word 会将此记录视为匹配项,因为 "Comedy" 在 pages.genre 中。我还必须保持对 organization_id 和 layout_id 的搜索。

感谢您对此提供的任何帮助。

您可以使用 SQL LIKEILIKE 运算符进行部分字符串匹配。一个简单的例子:

genre_name = "Drama"
Article.where("genre LIKE ?", "%#{genre_name}%")

这将生成 SQL 查询:

SELECT "articles".* FROM "articles" WHERE (name LIKE '%Drama%')

ILIKELIKE的不区分大小写的妹妹。百分号将匹配搜索词前后的零个或多个字符,因此在本例中,如果文章的类型为 'Comedy, Drama'.

,它也会匹配

最终的解决方案是:

@performances = Performance.includes(:production_page)
   .where("pages.genre LIKE ?", "%#{genre}%").references(:production_page)

感谢所有提供帮助的人。