销毁空白嵌套属性 [英] Destroy on blank nested attribute

查看:15
本文介绍了销毁空白嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果嵌套模型的属性在父模型的表单中被清除,我想销毁它 - 但是,如果模型为空,则 ActiveRecord::Callbacks 似乎不会被调用.

I would like to destroy a nested model if its attributes are blanked out in the form for the parent model - however, it appears that the ActiveRecord::Callbacks are not called if the model is blank.

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

我有一个艺术家表单,它使用 fields_for 来显示艺术家相关巡演日期的字段,用于编辑和添加新巡演日期,但如果我只是将巡演日期留空(删除它),destroy_if_blank 永远不会被调用.大概艺术家控制器的 @artist.update_attributes(params[:artist]) 行不考虑值得更新的空白实体.

I have a form for Artist which uses fields_for to show the fields for the artist's associated tour dates, which works for editing and adding new tour dates, but if I merely blank out a tour date (to delete it), destroy_if_blank is never called. Presumably the Artist controller's @artist.update_attributes(params[:artist]) line doesn't consider a blank entity worth updating.

我错过了什么吗?有没有办法解决这个问题?

Am I missing something? Is there a way around this?

推荐答案

如果where"或when"为空,则在accepts_nested _attributes 行上,您有代码表明记录应被忽略,删除reject_if 和您的 destroy_if 空白可能会被调用.

You have code that says the record should be ignored if the 'where' or the 'when' is blank, on the accepts_nested _attributes line, remove the reject_if and your destroy_if blank will likely be called.

通常要销毁,您需要在嵌套记录上设置 _destroy 属性,查看文档 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Typically to destroy, you would set a _destroy attribute on the nested record, check out the docs http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

另外,今天刚刚使用了 cocoon,并认为它很棒,https://github.com/nathanvda/cocoon

Also, just used cocoon for some of this today, and thought it was awesome, https://github.com/nathanvda/cocoon

这篇关于销毁空白嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆