使用嵌套属性删除验证

时间:2015-04-30 08:57:12

标签: ruby-on-rails ruby-on-rails-4

我有一个带有嵌套属性的Rails表单。用户可以通过两种方式更新其caddy

  • 将其传递地址写入模型Address的嵌套属性,
  • 或者选中一个复选框,意思是"我不想发送"

它产生了一组这样的参数:

{
  "id"=>"mine",
  "caddy"=> {
    "address_attributes"=>{"street"=>"", "city"=>"" [...]},
    "use_address"=>"1"
  }
}

我模特的某些部分:

Model Caddy < AR::Base
  belongs_to :address
  accepts_nested_attributes_for :address
  attr_accessor :use_address
end

Model Address < AR::Base
  validates :street, :presence => true
end

问题在于,当用户选中use_address复选框时,不应使用address_attributes,但它们是,street存在会引发验证错误。

我尝试将此方法添加到Caddy以覆盖use_addresss=生成的attr_accessor

def use_address=(v)
  if v == '1'
    self.address_id = nil
    self.address_attributes = {}
    self.address = nil
  end
  super
end

但它什么都没改变(address_attributes应该是nil然后是哈希参数。)

我找到的唯一解决方案是将params直接更改为我的控制器,但它很糟糕。你有其他解决方案吗?

1 个答案:

答案 0 :(得分:1)

我通常会覆盖assign_attributes

def assign_attributes(attrs)
  unless ActiveRecord::ConnectionAdapters::Column.value_to_boolean(attrs.delete(:use_address))
    self.address && self.address.mark_for_destruction
    # or self.address_id = nil if you don't want to destroy existing address
    attrs.delete(:address_attributes)
  end
  super(attrs)    
end