【问题标题】:How do I prevent my last nested attribute from being destroyed?如何防止我的最后一个嵌套属性被破坏?
【发布时间】:2012-09-23 11:05:04
【问题描述】:

我有一个客户模型,它有_许多这样的手机;

class Customer < ActiveRecord::Base
  has_many :phones, as: :phoneable, dependent: :destroy
  accepts_nested_attributes_for :phones, allow_destroy: true
end

class Phone < ActiveRecord::Base
  belongs_to :phoneable, polymorphic: true
end

我想确保客户始终拥有至少一种嵌套电话型号。目前我在浏览器中管理这个,但我想在服务器上提供一个备份(我遇到了几个没有电话的客户记录,不太清楚他们是怎么做到的,所以我需要一个支持) .

我认为这必须在模型中实现,但我不太确定如何做到这一点。到目前为止,我所有的尝试都失败了。我认为电话模型中的 before_destroy 回调是我想要的,但我不知道如何编写它以防止模型被破坏。如果父模型已被破坏,我还需要它来允许模型的破坏。有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails activerecord callback nested-attributes


    【解决方案1】:

    你可以这样做:

    before_destory :check_phone_count
    
    def check_phone_count
      errors.add :base, "At least one phone must be present" unless phonable.phones.count > 1
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 2015-04-28
      相关资源
      最近更新 更多