【问题标题】:Ruby on Rails - Run after_save only if new recordsRuby on Rails - 仅在新记录时运行 after_save
【发布时间】:2017-05-15 11:44:19
【问题描述】:

在我的应用程序中,我有模型 PostImage。我的协会是:

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

我将cocoon gem 用于nested_forms

当用户添加图片时,我有一些全局设置,用户可以将这些设置应用于他们正在添加的图片。

我是这样做的:

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

这很好用,但现在我想要它,所以如果他们想edit post's images,我想将相同的发布全局设置 ONLY应用于新记录

我尝试这样做:

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

这根本不起作用,全局设置没有添加到任何记录中(也没有添加到new/createedit/update 操作)

我也试过:

after_save :global_settings, if: new_record?

这给了我错误:undefined method 'new_record?' for Post

我怎样才能只为所有新记录/新图像应用我的全局设置?

ps:我试图在 SO 上找到一些答案,但没有任何效果!

【问题讨论】:

    标签: ruby-on-rails-4 associations updates before-save after-save


    【解决方案1】:

    这可能对你有用。

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

    【讨论】:

    • 谢谢@Vikram。是的,如果只想在 post 是新的时应用它,那可以工作,但在我的情况下,我还想在 post 不是新的但添加的图像是新的时应用全局设置。
    • 在这种情况下,只需将相同的代码添加到图像模式。应用全局设置的代码应该在 image.rb 中说什么?
    【解决方案2】:

    由于images 没有那些全局设置 意味着您只能在没有所有fieldsimages 上执行function

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多