1

Trying to create a search method in my model and join conditions based on arguments passed to the method. However, nothing gets chained after the initial "where"

Controller:

Item.search(args)

Model:

  def self.search(args = {})
    include ActsAsTaggableOn # Tagging model for search

    result = where("title LIKE ? OR description LIKE ? OR tags.name LIKE ?", "%#{args[:search]}%", "%#{args[:search]}%", "%#{args[:search]}%")
      .joins("JOIN taggings ON taggings.taggable_id = items.id")
      .joins("JOIN tags ON taggings.tag_id = tags.id")

      # Categories
      if args[:categories]
        result.where(:category_id => args[:categories])
      end

      # Order
      if args[:order] == "category"
       result.joins(:categories).order("categories.title ASC")
      else
        result.order("title DESC")
      end


      # Pagination
      result.paginate(:per_page => 10, :page => args[:page])

end

Even if I strip out the if block and do a chain directly afterwards, it doesn't work:

result = where(:foo => "bar")
result.order("name DESC")

... runs just the where.

Any ideas?

Thank in advance.

0

1 Answer 1

3

What you should do is chain it by adjusting the definition of result as you go:

result = result.where(...)

Each time you must re-assign back to result with the updated scope. This is because result.where returns a new scope, it does not adjust the existing scope.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.