I have a situation where I have an array constant that I'd like to perform a string search on through a scope. I usually use AR to accomplish this but wasn't sure how to incorporate this with a static array. Obviously using a where
clause wouldn't work here. What would be the best solution?
class Skills
SALES_SKILLS = %w(
Accounting
Mentoring
...
)
# Search above array based on "skill keyword"
scope :sales_skills, ->(skill) { }
end
CodePudding user response:
May be using Enumerable#grep
and convert string to case ignoring regexp with %r{}
literal
class Skills
SALES_SKILLS = %w(
Accounting
Mentoring
#...
)
def self.sales_skills(skill)
SALES_SKILLS.grep(%r{#{skill}}i)
end
end
Skills.sales_skills('acc')
#=> ["Accounting"]
Skills.sales_skills('o')
#=> ["Accounting", "Mentoring"]
Skills.sales_skills('accounting')
#=> ["Accounting"]
Skills.sales_skills('foo')
#=> []
CodePudding user response:
It would be better to create a method for this as you want to return a string. Scope is designed to return an ActiveRecord::Relation:
Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as where, joins and includes. All scope bodies should return an ActiveRecord::Relation or nil to allow for further methods (such as other scopes) to be called on it.
Reference: https://guides.rubyonrails.org/active_record_querying.html#scopes
CodePudding user response:
I would do this:
class Skills
SALES_SKILLS = %w(
Accounting
Mentoring
#...
)
def self.sales_skills(skill)
SALES_SKILLS.select do |sales_skill|
sales_skill.downcase.include?(skill.downcase)
end
end
end
Skills.sales_skills('cc')
#=> ["Accounting"]
Skills.sales_skills('o')
#=> ["Accounting", "Mentoring"]
Skills.sales_skills('accounting')
#=> ["Accounting"]
Skills.sales_skills('foo')
#=> []