简体   繁体   中英

Creating a scope from an array constant

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

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

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')
#=> []

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')
#=> []
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM