3

I'm doing a search on a model using a scope. This is being accessed by a search form with the search parameter q. Currently I have the code below which works fine for searches on tags associated with the model. But I would also like to search the title field. If I add to this scope then I will get all results where there is a tag and title matching the search term.

However, I need to return results that match the company_id and category_id, and either/or matching title or tag. I'm stuck with how to add an OR clause to this scope.

  def self.get_all_products(company, category = nil, subcategory = nil, q = nil)
    scope = scoped{}
    scope = scope.where "company_id = ?", company
    scope = scope.where "category_id = ?", category unless category.blank?
    scope = scope.tagged_with(q) unless q.blank?
    scope
  end

I'm using Rails 3.

robzolkos
  • 2,196
  • 3
  • 30
  • 47
  • Can you explain what you ended up doing. I'm also using acts-as-taggable-on and want the query to return results that match either the company name or any tags associated with the record – you786 Apr 17 '12 at 01:27

2 Answers2

3

Ever consider Arel? You can do something like this

t = TableName.arel_table
scope = scope.where(t[:title].eq("BLAH BLAH").or(t[:tag].eq("blah blah")))

or else you can do

scope = scope.where("title = ? OR tag = ", title_value, tag_value)
bokor
  • 1,829
  • 1
  • 19
  • 25
  • 1
    This doesn't work as the tags are stored in a separate table and doesn't actually belong to the table that the OP wants to query. – Noz Jul 11 '12 at 23:44
  • yep, shouldn't be accepted. The question is about acts_as_taggable and this does not work… or am I missing something ? – Ben Nov 29 '14 at 16:02
0

I could be wrong, but I don't think scopes can help you to construct an or condition. You'll have to hand-write the code to buid your where clause instead. Maybe something like this...

clause = "company_id=?"
qparams = [company]

unless category.blank?
    clause += " or category_id=?"
    qparams <= category
end

scope.where clause, *qparams
Steve Jorgensen
  • 11,725
  • 1
  • 33
  • 43