用于搜索的 Rails Gem [英] Rails Gem for Searching

查看:29
本文介绍了用于搜索的 Rails Gem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络应用程序,我想在其中提供高级搜索,用户可以在其中输入任意数量的由 AND 和/或 OR 连接的查询,如下所示:

I have a webapp where I want to provide an advanced search in which the user enters an arbitrary amount of queries joined by AND's and/or OR's, like this:

(在网页搜索框中输入)

(entered into the search box on the webpage)

name = "john" OR (occupation = "gardener" AND hobby.main = "reading")

在之前的帖子中,我成功实现了一个系统,我直接将上述格式的查询转换为有效的 SQL 语句,并将它们直接输入到 SQL 中以查询数据库.

In a prior post, I successfully implemented a system in which I directly convert queries formatted as above into valid SQL statements, and feed them straight into SQL to query the database.

这行得通,但现在我担心三件事:

This worked, but now I worry about three things:

  1. 这是 SQL 注入的严重后果
  2. 如果用户的输入无效,SQL 会抛出一个不太好的错误......处理这些异常时遇到了一些麻烦(尽管这部分是可行的).
  3. 代码看起来很笨拙,我想知道是否有更好的方法.

嗯,我听说有一个更好的方法,那就是使用搜索宝石.

Well, I've heard there is a better way, by using search gems.

但是,我一直无法找到符合我需求的宝石.许多宝石似乎 complex 对于我需要的东西,我发现的任何内容都没有明确说明您如何具体实现我正在寻找的内容 - 用户输入的位置由 AND/OR 语句连接的动态数量的查询.

However, I've been having trouble finding gems that match my needs. Many of the gems seem too complex for what I need, and nothing that I've found made it clear exactly how you could implement specifically what I'm looking for -- where the user enters a dynamic number of queries joined by AND / OR statements.

像我现在所做的那样,将语句直接转换为 SQL 语法并直接注入它的成本究竟有多大?将这些宝石中的一种融入我想要的东西有多容易?有经验的"Rails 开发人员会做什么?我是 Rails 的完全新手,所以我没有任何这方面的经验.

Exactly how costly is it to just convert the statement straight to SQL syntax and inject it right in, like I'm doing right now? How easy is it to incorporate one of these gems for what I want? What would an "experienced" Rails developer do? I'm a complete noobie to Rails, so I don't have experience with any of this.

推荐答案

有一个名为 Ransack

它允许您以非常简单的方式搜索模型:

Which allows you to search models in a very easy way:

<%= f.search_field :name_or_description_or_email_or_articles_title_cont %>

上面的例子是一个标签,当点击时会在名称或描述或电子邮件或文章标题列中搜索,其中包含搜索文本字段中提供的内容

The example above is a label when clicked wil search in a name or description or email or article_title column containing what ever was provided in the search text field

这是引擎盖下的洗劫示例

Heres an example of ransack underneath the hood

>> User.ransack(first_name_cont: 'Rya').result.to_sql
=> SELECT "users".* FROM "users"  WHERE ("users"."first_name" LIKE '%Rya%')

使用简单,可根据需要用于高级搜索

Its simple to use and can be used for advanced search if required

这篇关于用于搜索的 Rails Gem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆