0

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
1
  • 2
    Is that scope relevant to your question? Without it, I’d say you just want to search an array. Commented Jul 25, 2022 at 18:10

3 Answers 3

1

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')
#=> []
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
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

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.