Home > database >  Rails WHERE method in the context of SCOPE for like ? syntax
Rails WHERE method in the context of SCOPE for like ? syntax

Time:05-23

I fail to find the right syntax for a WHERE method in the context of a SCOPE. My classified MODEL has several SCOPE that works well to filter classifieds by category or area:

#in the model  
scope :filter_by_category, -> (category) {where category: category}
scope :filter_by_area, -> (area) {where area: area}

I want to do a more advanced SCOPE filter to search for classifieds' Titles containing a specific string. Outside of SCOPE I would generally retrieve the data with:

Classified.where("title like ?", "%title%")

But in the context a SCOPE, I do not manage to find the right syntax and keep getting some errors (unexpected ->, expecting `end' scope [...]). I tried the following:

scope :filter_by_title -> (title) { where ("title like ?","%title%")}
scope :filter_by_title -> (title) { where ("like ?","%title%")}

Both give me syntax error. Could anyone help me find the right syntax please?

CodePudding user response:

You have three problems:

  1. The lambda is an argument to scope to you need a comma after the symbol:

     scope :filter_by_title, -> ...
     # --------------------^
    
  2. Whitespace matters in Ruby so f (x, y) and f(x, y) are different things. The parentheses in f (x, y) are expression grouping parentheses whereas in f(x, y) they're method calling parentheses. So f (x, y) is a syntax error because x, y isn't an expression. Remove the stray space:

    scope :filter_by_title, ->(title) { where('title like ?', ...
    # ---------------------------------------^ No more space here
    
  3. You want to use string interpolation to expand the title argument to the scope:

    scope :filter_by_title, ->(title) { where('title like ?', "%#{title}%") }
    # ----------------------------------------------------------^^-----^ Interpolation
    

CodePudding user response:

Use interpolation:

scope :filter_by_title, -> (title) { where("title like ?","%#{title}%") }

# Classified.filter_by_title("another title")

https://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-scope

  • Related