ActiveRecord查找始于 [英] ActiveRecord find starts with

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

问题描述

一个非常简单的问题-我如何进行搜索以查找名称以ActiveRecord中的某个字符串开头的所有记录。我在互联网上看到过各种各样的地方,都使用了逐字样的LIKE SQL子句-但据我所知,这不是正确的方式。

Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I've seen all sorts of bits all over the internet where verbatim LIKE SQL clauses are used - but from what I've heard that isn't the 'correct' way of doing it.

是否有正确的 Rails方式?

Is there a 'proper' Rails way?

推荐答案

我强烈推荐 Searchlogic 插件。

然后就这么简单:

@search = Model.new_search(params[:search])
@search.condition.field_starts_with = "prefix"
@models = @search.all

Searchlogic足够聪明,就像ActiveRecord一样可以使用在 starts_with 条件下的字段名称上。

Searchlogic is smart enough, like ActiveRecord, to pick up on the field name in the starts_with condition. It will also handle all pagination.

此方法将有助于防止SQL注入,并且与数据库无关。 Searchlogic最终会根据您使用的数据库适配器对搜索进行不同的处理。您也不必编写任何SQL!

This method will help prevent SQL injection and also will be database agnostic. Searchlogic ends up handling the search differently depending on the database adapter you're using. You also don't have to write any SQL!

Searchlogic拥有出色的文档并且易于使用(我是Ruby和Rails的新手)。当我陷入困境时,该插件的作者甚至在几小时内回复了一封直接电子邮件,帮助我解决了问题。我不能推荐足够的Searchlogic ...如您所知。

Searchlogic has great documentation and is easy to use (I'm new to Ruby and Rails myself). When I got stuck, the author of the plugin even answered a direct email within a few hours helping me fix my problem. I can't recommend Searchlogic enough...as you can tell.

这篇关于ActiveRecord查找始于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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