Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 拒绝散列中的空散列_Ruby On Rails_Ruby_Hash - Fatal编程技术网

Ruby on rails 拒绝散列中的空散列

Ruby on rails 拒绝散列中的空散列,ruby-on-rails,ruby,hash,Ruby On Rails,Ruby,Hash,我在params中得到了这个哈希 `用户组属性 => {"0"=>{"name"=>"hello", "id"=>"1", "_destroy"=>"false", "user_ids"=>["201"]}, "1"=>{"name"=>"hello2", "id"=>"2", "_destroy"=>"false", "user_ids"=>["83"]}, "2"=> {"name"=>"ddddddddd

我在params中得到了这个哈希 `用户组属性

=> {"0"=>{"name"=>"hello", "id"=>"1", "_destroy"=>"false", "user_ids"=>["201"]},
 "1"=>{"name"=>"hello2", "id"=>"2", "_destroy"=>"false", "user_ids"=>["83"]},
 "2"=>
  {"name"=>"dddddddddd", "id"=>"5", "_destroy"=>"false", "user_ids"=>["256"]},
 "3"=>{"name"=>"", "id"=>"", "_destroy"=>"false"}}`

我需要拒绝id为“”的所有内容。如何操作?

如果您使用的是
嵌套的\u属性
,则可以执行此操作

hash = {"0"=>{"name"=>"hello", "id"=>"1", "_destroy"=>"false", "user_ids"=>["201"]},
 "1"=>{"name"=>"hello2", "id"=>"2", "_destroy"=>"false", "user_ids"=>["83"]},
 "2"=>
  {"name"=>"dddddddddd", "id"=>"5", "_destroy"=>"false", "user_ids"=>["256"]},
 "3"=>{"name"=>"", "id"=>"", "_destroy"=>"false"}}

hash.reject!{|a, b| b["id"].empty?}
#=> {"0"=>{"name"=>"hello", "id"=>"1", "_destroy"=>"false", "user_ids"=>["201"]}, "1"=>{"name"=>"hello2", "id"=>"2", "_destroy"=>"false", "user_ids"=>["83"]}, "2"=>{"name"=>"dddddddddd", "id"=>"5", "_destroy"=>"false", "user_ids"=>["256"]}}
accepts_nested_attributes_for :user_groups, reject_if: lambda{|attr| attr[:id].blank?} 

我知道您没有在问题或标记中指定Rails,但我觉得这个问题仍然很难回答。

首先向我们展示您为此编写的代码。对我们来说,更正代码比编写代码更容易,也更好,然后您必须将代码硬塞进程序中。不过,作为一个起点,是您的朋友。Mary,由于Vimsha的计算中没有使用
hash
键的值,因此块变量
a
可以替换为下划线(作为占位符),如果您希望提请注意这一事实:
hash.reject!{| |,b | b[“id”]为空?}