链接轨道3中的子句

时间:2012-10-09 23:48:39

标签: activerecord ruby-on-rails-3.2

我为搜索输入做了一个基于两个参数的小搜索方法。我的代码是这样的:

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

正如你们所看到的那样,它非常丑陋。工作,但很难看。

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

希望你们能给我一些指导。

提前致谢

1 个答案:

答案 0 :(得分: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