gpt4 book ai didi

ruby-on-rails - 使用 will_paginate/searchlogic 搜索多个字段

转载 作者:行者123 更新时间:2023-12-04 06:41:30 25 4
gpt4 key购买 nike

您如何在模型的多个字段中进行有效搜索?

# user.rb model
def self.search(search, page)
paginate :per_page => 20, :page => page,
:conditions =>
['name like ? OR notes like ? OR code like ? OR city like ? OR state like ?,
"%#{search}%","%#{search}%","%#{search}%","%#{search}%","%#{search}%"
], :order => 'name'

这段代码对于多个字段来说是可怕的,并且如果单词 #1 来自 :name 而单词 #2 来自 :code,则它不会返回结果。有没有更优雅的方式?

最佳答案

我认为这行得通

def self.search(search, page)
fields = [:name, :notes, :code, :city, :state]
paginate :per_page => 20, :page => page,
:conditions => [fields.map{|f| "#{f} like ?"}.join(' OR '),
*fields.map{|f| "%#{search}%"}], :order => 'name'

关于ruby-on-rails - 使用 will_paginate/searchlogic 搜索多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4176650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com