2013-05-13 47 views
2

我试图拒绝一个空的表单条目,但我有困难。我如何使用除了嵌套散列中的拒绝

用户既可以选择现有位置,也可以创建一个新位置。我希望表单实际显示空白字段,但是当它们全部为空时拒绝它们。由于'_destroy'永远不会是空的,我需要做个例外。如果只填写数量,则可以拒绝该条目。

表单提交下列资料:

参数:

{"product"=> 
     {..., 
     "product_locations_attributes"=> 
      { 
      "0"=>{"location_attributes"=>{"_destroy"=>"false", "street"=>"", "number"=>"", "zipcode"=>"", "city"=>"", "country"=>""}, "quantity"=>""}, 
      "1"=>{"_destroy"=>"false", "location_id"=>"", "quantity"=>""}} 
      } 
     , "commit"=>"Create Product" 
     } 

A我试图让空位置在产品模型中移除如下:

accepts_nested_attributes_for :product_locations, :allow_destroy => true, 
    :reject_if => proc {|a| a.except('_destroy', 'quantity').values.all?(&:blank?)} 

因为它是嵌套的,它不会像这样工作。 那么如何检查除数量和_destroy之外的所有物品是否空白? 应该可以一次完成它吗? 感谢您的帮助。

*更新,以使其更清晰*

+0

数据,就像你写的那样,是一个'Array'。你的意思是提供一个'哈希'? – rossta 2013-05-13 12:21:57

+0

嗯,好点。也许我需要更好地了解我想要做的事情。 – Fritzz 2013-05-13 12:33:07

+0

@Fritzz在'proc'中,是'a'那个数组? – Stefan 2013-05-13 12:38:54

回答

0

感谢@RobHeaton的服务员,我终于完成了这项工作。 Myabe他的回答可以工作,但它对我没有用。如果它应该和我做错了,让我知道,我会接受他的答案。我终于得到它与下面的代码工作:

accepts_nested_attributes_for :product_locations, :allow_destroy => true, :reject_if => :empty_fields 

    def empty_fields(a) 
    if la = a[:location_attributes] 
     la[:street].blank? && la[:number].blank? && la[:city].blank? && la[:zipcode].blank? && la[:country].blank? 
    else 
     a[:location_id].blank? 
    end 
    end 

它现在很清楚什么需要是空白,以便它拒绝。我尝试过其他的事情,结果是接受或拒绝了太多的事情。 只要写下来以防其他人遇到同样的问题。

0

我会明确地检查可能会或可能不会是空白的,而不是试图做一些的各个领域“是他们都空白”。更加明确和可读。

:reject_if => proc {|a| 
    location_attributes = a[:location_attributes] 
    a[:street].blank? && a[:number].blank? && a[:location_id].blank? 
} 

从长远来看,它会变得冗长但更好!

+0

感谢您的回答。我希望将一个.except作为一个更灵活的解决方案,以防将新字段添加到地址中,但是,好吧,我喜欢你的论据,因为它更加冗长和可读。 问题在于,在此解决方案中,使用现有位置的新product_locations(原始问题中的product_location [1]),现在也由于未找到location_attributes而被拒绝。至少这就是我现在看到的,我正在尝试你的解决方案..或者是其他的错误? – Fritzz 2013-05-15 07:08:06

+0

没问题 - 在这种情况下,传入proc的属性哈希是什么样的? – RobHeaton 2013-05-15 08:36:27

+0

属性散列具有使用一个新的位置,或一个现有的,象这样product_locations: “产品”=> { “product_locations_attributes”=> { \t \t \t “1”=> \t \t \t \t { “location_attributes”=> \t \t \t \t \t { “_destroy”=> “假”, “街道”=> “Esmoreitstraat”, “数量”=> “60”, “邮政编码”=> “1017 DT”, “city”=>“阿姆斯特丹”,“国家”=>“荷兰”},“数量”=>“3”}, \t \t \t “2”=> \t \t \t \t { “_destroy”=> “假”, “LOCATION_ID”=> “1”, “数量”=> “”, “ID”=> “110”}, \t \t \t “3”=> \t \t \t \t { “_destroy”=> “假”, “LOCATION_ID”=> “”, “数量”=> “3”} \t \t \t} “提交“=>”创建产品“ } 1是新的,2是存在的,3是无效的。 – Fritzz 2013-05-15 09:09:39