0

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

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,我只想将相同的帖子全局设置 应用于新记录

我试图这样做:

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上找到一些答案,但没有任何效果!

4

2 回答 2

0

这可能对你有用。

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
于 2017-05-15T12:50:52.013 回答
0

因为images没有那些全局设置意味着你只能执行functiononly on imagesthat 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
于 2017-05-18T10:10:10.013 回答