0

I've got a rails model that accepts a title and a url that are both strings to allow users to put a link to an article on their profile page. I've got a certain link that won't save and I'm not sure why.

Here is the link: https://khabar.ndtv.com/news/bollywood/katrina-kaif-sidharth-malhotra-aditya-roy-kapur-prepping-or-avengers-viral-video-1845153?pfrom=home-bollywood

My model is named CompanyProfileNewsLink and here is what I'm doing in the console to test:

n = CompanyProfileNewsLink.new
n.id = 1
n.title = "Indian article"
n.url = "https://khabar.ndtv.com/news/bollywood/katrina-kaif-sidharth-malhotra-aditya-roy-kapur-prepping-or-avengers-viral-video-1845153?pfrom=home-bollywood"
n.company_id = 1
n.save

It responds with:

(0.2ms)  BEGIN

and it hangs up there and never responds with COMMIT. I've tried various variations of that url and all of them save fine. If I remove the ? and the = from the link, it will save, but with either of those in the string, it won't save. Now, I can update an existing record and put that url in and it updates fine. Any ideas? It's strange.

I'm using a gem named MetaInspector and it grabs the metadata from a link. Here is the model:

class CompanyProfileNewsLink < ApplicationRecord
  belongs_to :company
  before_validation :smart_add_url_protocol
  validates_presence_of :title, :url
  validates_format_of :url, :with => /\A(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w\.-]*)*\/?\Z/i, :on => :create
  validate :check_link

protected

  def smart_add_url_protocol
    unless self.url[/\Ahttp:\/\//] || self.url[/\Ahttps:\/\//]
      self.url = "http://#{self.url}"
    end
  end

  def check_link
    begin
      news_link = MetaInspector.new(url, :connection_timeout => 12, :read_timeout => 7, :retries => 3)
    rescue MetaInspector::RequestError, MetaInspector::ParserError
      errors.add(:url, "#{url} is either not available or not correct.")
    rescue MetaInspector::TimeoutError
      errors.add(:url, "#{url}) has timed out.")
    end
  end
end
Paul
  • 170
  • 2
  • 9
  • Show the model please – Jagdeep Singh May 03 '18 at 14:17
  • 2
    This `n.id = 1` is bad idea. Leave setting `id` to the database itself. – Jagdeep Singh May 03 '18 at 14:18
  • Yes, I should've left the id up to the database. Thanks. I've added the model to the original post. I would think if it was a problem with the regex that it would give me an error rather than just not saving. I'm still quite new to all this. Thanks for looking at it! – Paul May 03 '18 at 14:52

1 Answers1

0

It looks like it was an issue with the regex I was using that wasn't allowing that url to go through. I ended up using a solution something like the one in this other question instead: Rails: What's a good way to validate links (URLs)?

Paul
  • 170
  • 2
  • 9