Rails 4 LIKE query - ActiveRecord adds quotes

前端 未结 7 1559
轮回少年
轮回少年 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

    0 讨论(0)
  • 2020-12-02 09:25

    While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

    def self.search(query, page=1)
      query = "%#{query}%"
      name_match = arel_table[:name].matches(query)
      postal_match = arel_table[:postal_code].matches(query)
      where(name_match.or(postal_match)).page(page).per_page(5)
    end
    
    0 讨论(0)
  • 2020-12-02 09:28

    If someone is using column names like "key" or "value", then you still see the same error that your mysql query syntax is bad. This should fix:

    .where("`key` LIKE ?", "%#{key}%")
    
    0 讨论(0)
  • 2020-12-02 09:32

    Try

     def self.search(search, page = 1 )
        paginate :per_page => 5, :page => page,
          :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'
      end
    

    See the docs on AREL conditions for more info.

    0 讨论(0)
  • 2020-12-02 09:41

    Your placeholder is replaced by a string and you're not handling it right.

    Replace

    "name LIKE '%?%' OR postal_code LIKE '%?%'", search, search
    

    with

    "name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"
    
    0 讨论(0)
  • 2020-12-02 09:44
    .find(:all, where: "value LIKE product_%", params: { limit: 20, page: 1 })
    
    0 讨论(0)
提交回复
热议问题