[英]Modify a child record in before_save callback
努力在其父级的 before_save 回调中修改子记录。
子记录是Photo
,它有一个名为main
的属性,它是一个布尔值。
父记录是Deal
, has_many :photos
用于修改记录的表单是嵌套的以更改deal
,用户还可以更改photo
属性或添加或删除photos
。
这是摩擦。 我需要始终拥有一张main
照片,我计划在 before_save 回调中执行此操作,在那里我检查照片,如果main
列表中没有照片,我将在列表中的第一张照片上将main
设置为 true .
它不会保存子记录,我希望它会。 我已经添加了调试语句,所以我可以证明正在调用该方法,我还可以声明 main 的值被标记为 true ......它只是没有被保存。 我误解了这个回调吗? 光棚会很棒。 谢谢你们!
class Deal < ActiveRecord::Base
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos, allow_destroy: :true
before_save :set_main_photo
### bunch of other unrelated stuff
private
def set_main_photo
if self.photos
if self.photos.main.nil?
self.photos.first.main = true
end
end
end
end
这里发生了一些事情,但您的主要问题是以这种方式修改子项不会自动保存记录。 您需要更新您的set_main_photo
以在子记录上调用.save
。 当你在做的时候,还有一些其他的变化是谨慎的:
def set_main_photo
if photos.any?
unless photos.main.present?
photos.first.update_attribute :main, true
end
end
end
完成此操作后,您现在以一种笨拙的方式将Deal
和Photos
结合在一起,在Photo
上有一个属性表示其与Deal
关系条件, Deal
Deal
管理该属性。 更好的方法是创建一个新的关系来对此进行建模,将属性的责任完全保留在Deal
:
class Deal
has_many :photos
belongs_to :main_photo, class_name: 'Photo'
end
class Photo
belongs_to :deal
end
这让您只需设置deal.main_photo = deal.photos.first
然后deal.save
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.