【发布时间】:2018-02-13 17:44:11
【问题描述】:
我有一个要求,用户可以在搜索框中键入内容,并且 Rails api 应该搜索任何客户字段以查找可能的匹配项,所以我开始这样并意识到这不是一个很好的解决方案,而且似乎很重复对于所有 5 个字段:
scope :filter, -> (term) { where(
"lower(customers.name) LIKE ? OR
lower(customers.email) LIKE ? OR
lower(customers.business_name) LIKE ? OR
lower(customers.phone) LIKE ? OR
lower(customers.doc_id) LIKE ? OR",
"%#{term.downcase}%", "%{term.downcase}%", "%#{term.downcase}%",
"%#{term.downcase}%", "%#{term.downcase}%"
) }
所以我了解了 Arel 并尝试了这个:
customers = Customer.arel_table
scope :filter, -> (term) { Customer.where(
customers[:name].matches("%#{term.downcase}%")).
or(customers[:email].matches("%#{term.downcase}%")).
or(customers[:phone].matches("%#{term.downcase}%")).
or(customers[:business_name].matches("%#{term.downcase}%").
or(customers[:doc_id].matches("%#{term.downcase}%"))
) }
但这同样是重复的。
有没有办法简单地使用任何一个版本?我在想也许对于 Arel 我可以这样做:
scope :filter, -> (term) { Customer.where(
customers[:name, :email, :phone, :business_name, :doc_id].matches("%#{term.downcase}%")
) }
更新
抱歉,但我忘了提及 - 我试图保持简单! - 如果有一个更简单的解决方案,它仍然需要是一个可链接的范围,因为我在其他范围的链中使用这个过滤器,就像在控制器中这样:
if params[:filter].present?
@cards = current_api_user.account.cards.new_card(:false).search(params.slice(:filter))
else ...
其中“搜索”是一个关注点,它只是将过滤器参数键/值对发送到模型中的范围。例如,这里是卡片模型范围(您可以看到它的过滤范围,然后调用 filter_customer 范围,然后调用 Customer.filter,这是问题所在)。这可能看起来很复杂,但这意味着我对所有这些相关模型的所有范围都具有完全的可组合性:
scope :new_card, -> value { where(is_new: value) }
scope :filter_template, -> (term) { Card.where(template_id: Template.filter(term)) }
scope :filter_customer, -> (term) { Card.where(customer_id: Customer.filter(term)) }
scope :filter, -> (term) { Card.filter_customer(term).or(Card.filter_template(term)) }
【问题讨论】:
标签: ruby-on-rails arel