與在before_save回調修改子記錄它的父掙扎。修改子記錄在before_save回調
子記錄是Photo
,它具有一個屬性main
這是一個布爾值。
父記錄是Deal
是has_many :photos
修改記錄的表格嵌套來進行更改deal
和用戶還可以更改photo
的屬性或添加或刪除photos
。
這裏是擦。我要始終有一個main
照片,我打算做一個before_save回調,在那裏我檢查的照片,並且如果在列表中沒有照片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
第一個例子只有在交易已被持續時纔有效。它可以通過使用'assign_attribute'來代替。但後來的例子首先是一個更好的主意。 – max