Rails 4 LIKE query - ActiveRecord adds quotes

前端 未结 7 1575
轮回少年
轮回少年 2020-12-02 09:07

I am trying to do a like query like so

def self.search(search, page = 1 )
  paginate :per_page => 5, :page =>          


        
7条回答
  •  情深已故
    2020-12-02 09:23

    Instead of using the conditions syntax from Rails 2, use Rails 4's where method instead:

    def self.search(search, page = 1 )
      wildcard_search = "%#{search}%"
    
      where("name ILIKE :search OR postal_code LIKE :search", search: wildcard_search)
        .page(page)
        .per_page(5)
    end
    

    NOTE: the above uses parameter syntax instead of ? placeholder: these both should generate the same sql.

    def self.search(search, page = 1 )
      wildcard_search = "%#{search}%"
    
      where("name ILIKE ? OR postal_code LIKE ?", wildcard_search, wildcard_search)
        .page(page)
        .per_page(5)
    end
    

    NOTE: using ILIKE for the name - postgres case insensitive version of LIKE

提交回复
热议问题