我有一个带有嵌套属性的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直接更改为我的控制器,但它很糟糕。你有其他解决方案吗?
答案 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