egervari
egervari

Reputation: 22512

refactoring a complex dynamic active relation query

I was wondering if I could get some refactoring help to make this query more concise.

Basically what this query does is it searches all the help_documents by some search terms. It checks the document question, content and the category it belongs to.

  def self.search(text)
    if text.blank?
      latest
    else
      relation = sorted.joins(:category)

      text.split(/\s/).each do |word|
        relation = relation.where(
            "lower(help_documents.question) like ? or lower(help_documents.content) like ? or lower(help_categories.name) like ?",
            "%#{word.downcase}%", "%#{word.downcase}%", "%#{word.downcase}%"
        )
      end

      relation
    end
  end

Compared to how you would do this in java/hibernate, this actually looks pretty good. But I figured the rails people might have even sexier tricks up their sleeve to accomplish the same thing. For example, there might be some methods/objects I don't know about that already do these types of things.

Upvotes: 0

Views: 275

Answers (1)

Jake Dempsey
Jake Dempsey

Reputation: 6312

I would first tidy this up by removing all the lower and downcase calls. If you are using mysql and your table is utf8 then the like will be case insensitive. That should remove some noise so we can look more at the problem.

Also, you can use named keys in the where:

relation.where("help_documents.question like :term, or help_documents.content like :term, or help_categories.name like :term", {:term => "%#{word}%"})

Also, you might want to check out squeel (http://metautonomo.us/projects/squeel/) which lets you even go further and gives you a lot of syntax sugar.

Upvotes: 2

Related Questions