0

This is a query run very infrequently (as admin), and it's not worth indexing/ using up RAM with sphinx.

So, with the variables set up something like this: fn, ln, em = 'John', 'Smith', '[email protected]'

The query is something like this:

profiles = Profile.joins(:user).where(:users=>{"email" => em}).
  where("first_name LIKE '%#{fn}%' AND last_name LIKE '%#{ln}%'")         

Except that I want the email to accept a substring (e.g. if em == 'th@gm', then it should match '[email protected]'). How do you write this to do a join selecting only those users with a variable matching a regex?

1 Answer 1

-1

(I got my inspiration from here):

Have you tried something like:

profiles = Profile.joins(:user).where("first_name LIKE ? AND last_name LIKE ?", "%#{fn}%", "%#{ln}%")
profiles.select{|p| p.user.email =~ /#{em}/}
Sign up to request clarification or add additional context in comments.

5 Comments

This is likely less efficient than a pure-SQL solution. Whether that's worth worrying about or not depends on how many Profiles there are likely to be that match the where clause but would fail the email test. If it's only a handful, this is probably a good solution. If there are many, it's less so.
Well, if we were aiming at efficiency, it would be better to use a stored procedure. However, since ActiveRecord's top priority isn't efficiency (and this is a Rails-esque question), I figured this is a workable answer.
Yes - this is a great solution. It's an essential query, but it is rarely required and not performance critical. There are many users, but it can be handled in memory at present - so a ruby select seems appropriate. Thanks!
@muistooshort: You're right. I was just copying the OP's code. I'll fix that.
mu, did a search and ended up looking at a previous answer of yours. Would you consider this safe from SQL injection? profiles = Profile.where("first_name LIKE '%#{fn.gsub(/[!%_]/) { |x| '!' + x }}%' ESCAPE '!' AND last_name LIKE '%#{ln.gsub(/[!%_]/) { |x| '!' + x }}%' ESCAPE '!'")

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.