如何使用Ruby中的ActiveRecord在字段中搜索一系列可选值?

Dav*_*Sag 1 ruby sql activerecord

我正在编写搜索查询,用户可以Item通过创建者,标题或描述或上述任意组合搜索s.

所以在我的搜索控制器逻辑中,我如此抓住了params:

creator = params['creator']
title = params['title']
description = params['description']
# todo: do some input validation here
results = nil
cr = User.roughly_named(creator).first
Run Code Online (Sandbox Code Playgroud)

我现在在做的是:

q = []
q << "creator_id IS #{cr.id}" if cr
q << "title LIKE '%#{title}%'" if title != ''
q << "description LIKE '%#{description}%'" if title != ''
results = Item.where(q.join(' AND ')
Run Code Online (Sandbox Code Playgroud)

但肯定有更好的方法.我愿意接受建议.

Jay*_*ayD 5

如何使用范围:

res = Item.scoped

res = res.where(["creator_id is ?", cr.id]) if cr
res = res.where(["title like ?", "%#{title}%"]) unless title.empty?
res = res.where(["description like ?", "%#{description}%"]) unless description.empty?
Run Code Online (Sandbox Code Playgroud)

在做的时候Item.scoped,你基本上做了延迟加载.迭代res将实际执行查询.链接可选的where子句时,这很方便.

PS:更喜欢?语法来防止SQL注入.