ruby-on-rails-4associationsupdatesbefore-saveafter-save

Ruby on Rails - Run after_save only if new records


In my application I have models Post & Image. My association are:

class Post < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images, reject_if: :image_rejectable?, allow_destroy: true

class Image < ActiveRecord::Base
  belongs_to :post

I use cocoon gem for nested_forms

When user is adding images, I have some global settings that user can apply to images they are adding.

I do it by doing:

class Post < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images, reject_if: :image_rejectable?, allow_destroy: true

  after_create :global_settings

  private

    def global_settings
      self.images.each { |image| image.update_attributes(
                            to_what: self.to_what,
                            added_to: self.added_to,
                            )
                      }
    end

This works fine, but now I want it so if they want to edit post's images, I want to apply same post global settings ONLY to new records.

I tried to do it by doing:

class Post < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images, reject_if: :image_rejectable?, allow_destroy: true

  after_save :global_settings

  private

  def global_settings
    if new_record?
      self.images.each { |image| image.update_attributes(
          to_what: self.to_what,
          added_to: self.added_to,
      )
      }
    end
  end

This didn't worked at all & global setting were not added to any record (nor on new/create or edit/update action).

I've also tried with:

after_save :global_settings, if: new_record?

This gave me error: undefined method 'new_record?' for Post

How can I only apply my global settings for all new records/new images?

ps: I tried to find some answer on SO, but nothing worked!


Solution

  • Since images doesn't have those global settings means that you can only execute the function only on images that doesn't have all fields.

    def global_settings
      self.images.each { |image|
        if image.to_what.blank?
          image.update_attributes(
              to_what: self.to_what,
              added_to: self.added_to
          )
        end
      }
    end