我在params中得到了这个哈希 `user_groups_attributes
=> {"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 =""。我怎么能这样做?
答案 0 :(得分:2)
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"]}}
答案 1 :(得分:0)
如果您使用nested_attributes
,则可以执行此操作
accepts_nested_attributes_for :user_groups, reject_if: lambda{|attr| attr[:id].blank?}
我知道你没有在问题或标签中指定Rails,但问题对我来说似乎仍然是Railsy。