0

I've some problem with an SQL Query

I've users which have skills

  def skills=(value)
    super(value.reject(&:blank?).join("|")) if !value.nil?
   end

  def skills
   super.present? ? super.split("|") : []
  end

Here is my problem. When I query on this field with "like", word order matter. How can I avoid that ?

User.where("skills LIKE '%car%driving_license%'")

Each user with skills which at least contain car and driving_license

User.where("skills LIKE '%driving_license%car%'")

Each user with skills which at least contain car and driving_license but in a different order

I want to be able to avoid this order problem. Any help ?

1
  • One option would be to split the skills string in your Ruby code, and then check each skill against a list of accepted skills, e.g. WHERE skill1 IN ('driving_license', 'car') AND skill2 IN ('driving_license', 'car') AND ... Commented Apr 21, 2016 at 14:35

2 Answers 2

1

If you sort the skills you can know the order and assemble a like query that will match both of them. You can create a migration to sort the existing skills.

def skills=(value)
  super(value.reject(&:blank?).sort.join("|")) if value
end

rails g migration sortUserSkills

User.where.not(skills: nil).each do u
  u.skills = u.skills
  u.save
end
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good idea, I'll try it and come back if it's work! Thanks
1

LIKE + OR queries are tough if my memory serves me. You can try ARel, but I think you lose LIKE.

2 things I can think of:

  1. Do the queries separately and combine results.

  2. Use something like this which may not work:

    conditions = ['%driving_license%car%', '%car%driving_license%'] User.where("skills LIKE ?", conditions)

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.