Safe ActiveRecord like query

后端 未结 5 494
别那么骄傲
别那么骄傲 2020-11-30 04:27

I\'m trying to write LIKE query.

I read that pure string quires aren\'t safe, however I couldn\'t find any documentation that explain how to write safe LIKE Hash Que

相关标签:
5条回答
  • 2020-11-30 04:49

    For PostgreSQL it will be

    Foo.where("bar ILIKE ?", "%#{query}%") 
    
    0 讨论(0)
  • 2020-11-30 04:53

    You can do

    MyModel.where(["title LIKE ?", "%#{params[:query]}%"])
    
    0 讨论(0)
  • 2020-11-30 04:57

    Using Arel you can perform this safe and portable query:

    title = Model.arel_table[:title]
    Model.where(title.matches("%#{query}%"))
    
    0 讨论(0)
  • 2020-11-30 05:01

    In case if anyone performing search query on nested association try this:

    Model.joins(:association).where(
       Association.arel_table[:attr1].matches("%#{query}%")
    )
    

    For multiple attributes try this:

    Model.joins(:association).where(
      AssociatedModelName.arel_table[:attr1].matches("%#{query}%")
        .or(AssociatedModelName.arel_table[:attr2].matches("%#{query}%"))
        .or(AssociatedModelName.arel_table[:attr3].matches("%#{query}%"))
    )
     
    

    Don't forget to replace AssociatedModelName with your model name

    0 讨论(0)
  • 2020-11-30 05:05

    To ensure that your query string gets properly sanitized, use the array or the hash query syntax to describe your conditions:

    Foo.where("bar LIKE ?", "%#{query}%")
    

    or:

    Foo.where("bar LIKE :query", query: "%#{query}%")
    

    If it is possible that the query might include the % character then you need to sanitize query with sanitize_sql_like first:

    Foo.where("bar LIKE ?", "%#{sanitize_sql_like(query)}%")
    Foo.where("bar LIKE :query", query: "%#{sanitize_sql_like(query)}%")
    
    0 讨论(0)
提交回复
热议问题