【发布时间】:2017-05-15 11:44:19
【问题描述】:
在我的应用程序中,我有模型 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,我想将相同的发布全局设置 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/create 或edit/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