我想销毁嵌套模型,如果其属性在父模型的形式中被遮盖了-但是,如果模型为空,则似乎未调用ActiveRecord::Callbacks
。
class Artist < ActiveRecord::Base
using_access_control
attr_accessible :bio, :name, :tour_dates_attributes
has_many :tour_dates, :dependent => :destroy
accepts_nested_attributes_for :tour_dates, :reject_if => lambda { |a| a[:when].blank? || a[:where].blank? }, :allow_destroy => true
validates :bio, :name :presence => true
def to_param
name
end
end
和
class TourDate < ActiveRecord::Base
validates :address, :when, :where, :artist_id, :presence => true
attr_accessible :address, :artist_id, :when, :where
belongs_to :artist
before_save :destroy_if_blank
private
def destroy_if_blank
logger.info "destroy_if_blank called"
end
end
我有一个用于Artist的表单,该表单使用
fields_for
显示与该艺术家相关的巡回日期的字段,该表单可用于编辑和添加新的巡回日期,但是如果我仅将巡回日期空白(以将其删除),则永远不会调用destroy_if_blank
。大概是Artist Controller 的@artist.update_attributes(params[:artist])
行不认为值得更新的空白实体。我想念什么吗?有没有解决的办法?
最佳答案
您有代码说如果“where”或“when”为空白,则应忽略该记录,请在accepts_nested _attributes行上,删除reject_if
并可能会调用您的destroy_if空白。
通常要销毁,您可以在嵌套记录上设置_destroy
属性,并查看docs http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
另外,今天只是用茧做些东西,以为真棒https://github.com/nathanvda/cocoon
关于ruby-on-rails - 销毁空白嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10943013/