ruby-on-railsbefore-savestack-level

Rails: before_save - Stack level too deep


I have this simple model:

class Post < ApplicationRecord

    after_create_commit :process
    before_save :re_process, on: :update

    has_one :processed, class_name: 'Post::Process'

    def process
        self.processed.destroy if self.processed
        processed = self.build_processed
        processed.save!
    end

    private

    def re_process
        self.process if self.title_changed?
    end

end

I get a Stack level to deep error everytime I create a new Post.

Now when I remove before_save :re_process, on: :update everything works fine.

Shouldn't this line take only affect when I am updating a post?


Solution

  • on: :update or on: :create doesn't work for before_save

    For this purpose, you have to use before_update

    class Post < ApplicationRecord
    
        after_create_commit :process
        before_update :re_process
    
        has_one :processed, class_name: 'Post::Process'
    
        def process
            self.processed.destroy if self.processed
            processed = self.build_processed
            processed.save!
        end
    
        private
    
        def re_process
            self.process if self.title_changed?
        end
    
    end
    

    If you are using on option with before_save, the callback will be executed no matter what is specified in on option.

    Hope this helps