0

I have the following code in my urlSearch model:

def find_url(orig_url)
    url = find_by(url: orig_url)
    unless url
        # some stuff
    end
end

Here find_by will search for the exact string passed to it which is : orig_url argument in my case.

For example, if in my table i have an url like : www.stackoverflow.com and if i search for http://stackoverflow.com or http://www.stackoverflow.com, it's not the same string which means that find_by will return nil.

Is there is a way to tell find_by to ignore http:// and www. when searching?

Dan
  • 2,701
  • 1
  • 29
  • 34
medBouzid
  • 7,484
  • 10
  • 56
  • 86

2 Answers2

1

You could do url = find_by(url: orig_url.gsub("http://" , ""))

And you'd need another gsub for "www."

Dylan Shields
  • 158
  • 1
  • 8
1

I don't see a direct way to do this. First, you have to extract the host from the string then remove www if it exists.

>> string = 'http://www.foobar.com'
>> host = URI.parse(string).host # www.foobar.com
>> host.gsub!(/^www\./, '') #foobar.com
>> MyModel.where('url LIKE ?', "%#{host}%").first

you should use LIKE (or ILIKE for postgresql) if you don't control the values stored in the database. you can't use find_by in this case since that will always find an exact match.

jvnill
  • 29,479
  • 4
  • 83
  • 86