scoped_search icon indicating copy to clipboard operation
scoped_search copied to clipboard

has_rich_text relation is not supported

Open istvan-ujjmeszaros opened this issue 4 years ago • 4 comments

We are using ActionText::RichText, which is using the has_rich_text relation, but scoped_search doesn't seem to have support for it so we can't search in the content of the rich_text field. Is there any workaround?

istvan-ujjmeszaros avatar Jan 09 '21 02:01 istvan-ujjmeszaros

If anyone else needs a workaround, I have ended up using this code:

class Snippet < ApplicationRecord
  has_rich_text :content

  scoped_search on: :title
  scoped_search relation: :content, on: :body, ext_method: :find_by_content

  def self.find_by_content(key, operator, value)
    { :conditions => sanitize_sql_for_conditions(["snippets.id IN (SELECT record_id FROM action_text_rich_texts WHERE record_type='Snippet' AND body ILIKE ?)", "%#{value}%"]) }
  end
end

I am leaving this open as it would be great if the gem would have built-in support for has_rich_text relations.

istvan-ujjmeszaros avatar Jan 09 '21 03:01 istvan-ujjmeszaros

~~I think this workaround has an SQL injection vulnerability.~~ Can anyone suggest a better way to do this or rewrite this to use a parameter? I had no luck with that.

istvan-ujjmeszaros avatar Mar 13 '21 05:03 istvan-ujjmeszaros

You should be able to use ? placeholders and sanitize_sql_for_conditions to prevent sql injection. See here

Something along the lines of this could work

class Snippet < ApplicationRecord
  has_rich_text :content

  scoped_search on: :title
  scoped_search relation: :content, on: :body, ext_method: :find_by_content

  def self.find_by_content(key, operator, value)
    value = "%#{value}%"
    sql = "id IN (SELECT record_id FROM action_text_rich_texts WHERE record_type='Snippet' AND body ILIKE ?)"
    { :conditions => sanitize_sql_for_conditions([sql, value]) }
  end
end

adamruzicka avatar Mar 15 '21 09:03 adamruzicka

Thanks, @adamruzicka, I just couldn't find the sanitizer methods on my own, sanitize_sql_for_conditions seems to work well here, and it is good to know that such methods exist!

istvan-ujjmeszaros avatar Mar 17 '21 06:03 istvan-ujjmeszaros