0

在我的应用程序中,我有型号Post & Image。我的联想是:Ruby on Rails - 仅在新记录时运行after_save

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 gemnested_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 

这工作得很好,但现在我想它,如果他们想editpost'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的答案,但没有任何工作!

回答

0

由于images没有这些全局设置意味着你只能只images执行function不都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 
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 
+0

谢谢@Vikram。是的,这可以工作,如果只想在'post'是新的时候应用它,但在我的情况下,我也希望在'post'不是新的时候应用全局设置,但添加的图片是新的。 – Rubioli

+0

在这种情况下,只需将相同的代码添加到图像模式。应用全局设置的代码应该在image.rb 什么说? –