首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >accepts_nested_attributes_for、reject_if和has_one的关系不能在一起工作?

accepts_nested_attributes_for、reject_if和has_one的关系不能在一起工作?
EN

Stack Overflow用户
提问于 2014-03-15 21:57:00
回答 3查看 3.4K关注 0票数 7

在我的模型中我有

代码语言:javascript
复制
has_one :order, dependent: :destroy

accepts_nested_attributes_for :order, reject_if: lambda { |order| order[:description].blank? }, allow_destroy: true

由于某些原因,尽管测试了reject_if并返回true (我用调试器检查了这一点),但是嵌套顺序并没有被破坏。

互联网上有很多关于这一现象的文章,但我找不到解决方案。

有人知道怎么解决这个问题吗?

EN

回答 3

Stack Overflow用户

发布于 2014-12-06 22:28:04

我最终创建了一个在这个特定场合设置销毁标志的智能"reject_if“,正如Destroy on blank nested attribute中所描述的那样,但是,根据我自己的规范,这不是非常"ruby",所以无法想象没有更好的解决方案了……

代码语言:javascript
复制
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)
}
票数 2
EN

Stack Overflow用户

发布于 2014-12-11 16:32:44

从nested_attributes API

您还可以设置一个:reject_if进程,以便在任何新的记录散列无法通过您的标准时忽略它们。

代码语言:javascript
复制
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:在您的模型中通过回调删除它们:

代码语言:javascript
复制
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属性

票数 1
EN

Stack Overflow用户

发布于 2014-12-06 16:41:42

尝尝这个

代码语言:javascript
复制
accepts_nested_attributes_for :order, reject_if: lambda { |order| order[:_destroy].blank? && order[:description].blank? }, allow_destroy: true
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22424730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档