Rails .where 任何字段都包含特定文本

Can*_*yer 1 ruby-on-rails

是否有一种快捷方式可以查询 Rails 数据库中包含特定文本段的字段的任何记录?我知道我可以用 a 对每个字段进行编码.where("field_name LIKE ?", "my text"),但是我有几个字段并且想知道是否有更短的方法来做到这一点。

提前致谢。

Hol*_*off 5

我不知道这样做的框架方式。你可以使用

my_attributes = YourModel.attributes
# delete attributes you do not need, like `id` etc.
# or just create an array with your desired attributes,
# whichever way is faster
queries = my_attributes.map { |attr| "#{attr} LIKE %insert_your_text_here%" } 
# Do not use this if the text your looking for is provided by user input.
built_query = queries.join(" OR ")
YourModel.where(built_query)
Run Code Online (Sandbox Code Playgroud)

这可以让你更接近你的目标。如果这对您有意义,请告诉我。

编辑:答案/sf/answers/3462064161/提到了 Ransack。这是一个不错的宝石,可以减轻您的负担。使它更容易,更好,性能更好:D

很高兴您喜欢这个,但请注意,如果您将用户输入作为您要查找的文本,请让您的应用程序打开以进行 sql 注入。(使用此解决方案) Ransack 会缓解这种情况。