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:
The lambda is an argument to
scope
to you need a comma after the symbol:scope :filter_by_title, -> ... # --------------------^
Whitespace matters in Ruby so
f (x, y)
andf(x, y)
are different things. The parentheses inf (x, y)
are expression grouping parentheses whereas inf(x, y)
they're method calling parentheses. Sof (x, y)
is a syntax error becausex, y
isn't an expression. Remove the stray space:scope :filter_by_title, ->(title) { where('title like ?', ... # ---------------------------------------^ No more space here
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