在我的模型中我有
has_one :order, dependent: :destroy
accepts_nested_attributes_for :order, reject_if: lambda { |order| order[:description].blank? }, allow_destroy: true由于某些原因,尽管测试了reject_if并返回true (我用调试器检查了这一点),但是嵌套顺序并没有被破坏。
互联网上有很多关于这一现象的文章,但我找不到解决方案。
有人知道怎么解决这个问题吗?
发布于 2014-12-06 22:28:04
我最终创建了一个在这个特定场合设置销毁标志的智能"reject_if“,正如Destroy on blank nested attribute中所描述的那样,但是,根据我自己的规范,这不是非常"ruby",所以无法想象没有更好的解决方案了……
accepts_nested_attributes_for :order, allow_destroy: true, reject_if: lambda { |attributes|
exists = attributes['id'].present?
empty = attributes[:description].blank?
attributes.merge!({_destroy: 1}) if exists and empty
return (!exists and empty)
}发布于 2014-12-11 16:32:44
从nested_attributes API
您还可以设置一个:reject_if进程,以便在任何新的记录散列无法通过您的标准时忽略它们。
params = { member: {
name: 'joe', order_attributes: [
{ description: 'Kari, the awesome Ruby documentation browser!' },
{ description: 'The egalitarian assumption of the modern citizen' },
{ description: '', _destroy: '1' } # this will be ignored
]
}}任何带有空白description的散列都将被完全忽略,即使它有_destroy标志。
如果您想删除具有空白描述的记录,我可以想到两个解决方案
选项1:在您的模型中通过回调删除它们:
before_save :remove_orders_without_description
def remove_orders_without_description
orders.select{|o| o.description.blank?}.each(&:delete)
end选项2:删除模型定义中的reject_if选项,并在视图中使用JS适当地设置_delete属性
发布于 2014-12-06 16:41:42
尝尝这个
accepts_nested_attributes_for :order, reject_if: lambda { |order| order[:_destroy].blank? && order[:description].blank? }, allow_destroy: truehttps://stackoverflow.com/questions/22424730
复制相似问题