消灭空白嵌套属性 [英] Destroy on blank nested attribute

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

问题描述

我想摧毁一个嵌套模式,如果它的属性形式父模型冲压出来 - 但是,它看来,如果该模型是空白的ActiveRecord ::回调不叫

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永远不会被调用。 presumably艺术家控制器的@ artist.update_attributes(PARAMS [:艺术家])。行不考虑空白实体值得更新

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?

推荐答案

您有code,说该记录应,如果',其中'或忽略了何时是空的,就在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 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 do destroy, you would set a _destroy attribute on the nested record, check out the docs http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

此外,只用茧一些这方面的今天,并认为这是真棒, https://github.com / nathanvda /茧

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

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

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