1

我已经完成了一个基于搜索输入的两个参数的小型搜索方法。我的代码是这样的:

def self.search(search, page)
    result = where("dead = ? and sold = ?", false, false)
    if not search.nil? and not search.empty?
        # regex for 'number - any word'
        search = search.split(' ')[0] if not (/^\d+ - .+$/ =~ search).nil?
        if not search.integer?
            result = result.where("name like ?", "%#{search}%")
        else
            result = result.where("earring = ?", search.to_i)
        end
    end
    result.paginate(:page => page)
        .includes(:mother, :father, :animal_type, :race)
        .order(:earring)
end

正如你们所看到的,它非常丑陋。有效,但很丑。

所以,我正试图找到一种方法让它变得更好......但不知道如何。

希望大家能给我一些指导。

提前致谢

4

1 回答 1

2
#in your model
scope :dead_and_sold, where('dead = :q AND sold = :q', :q => false)


#your search method
def self.search(search, page)
     result = dead_and_sold
     unless search.nil? && search.empty?
         # regex for 'number - any word'
         search = search.split(' ').first unless (/^\d+ - .+$/ =~ search).nil?

         result = unless search.instance_of?(Fixnum)
            result.where("name like ?", "%#{search}%")
         else
            result.where("earring = ?", search.to_i)
         end
     end


    result.paginate(:page => page)
       .includes(:mother, :father, :animal_type, :race)
       .order(:earring)

end
于 2012-10-10T11:05:13.723 回答