Search code examples
ruby-on-railsrubymethodsmodelopen-uri

Rails after_save method trying to update record over and over


I'm having a weird issue, my app seem to get stuck in a loop.

I have a model called Pages which allows the user to input a URL on save I have a after_save method called process_pages which looks as follows

pages.rb (model)

class Page < ActiveRecord::Base
  require 'open-uri'

  after_save :process_pages

  def process_pages
    self.html = open(self.url).read
    self.save
  end 
end

On saving the URL I can see in the development console that it get the HTML of the site but tries to constantly save the record over and over again stalling the page and I have to manually exit the server.

When I start back up again the record has been added and works as expected until I add another URL?

Is there anything wrong with my code which might be causing this continuous loop?

Thanks for reading!


Solution

  • If you need to call process_pages only once after Creating a Page record and not after Updating a Page record then I would suggest to use after_create instead.

    class Page < ActiveRecord::Base
      require 'open-uri'
    
      after_create :process_pages
    
      def process_pages
        self.html = open(self.url).read
        self.save
      end 
    end
    

    With after_save :process_pages, process_pages method would be called every time you save a Page record. You are saving a Page record again within process_pages method which triggers the after_save callback and you start looping.

    See this SO Question for difference between after_save and after_create. You will understand better as to why you are going in loops.