Mary Dear
Mary Dear

Reputation: 185

Reject empty hash from hash

I got this hash in 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"}}`

and I need reject all with id = "". how can I do it?

Upvotes: 0

Views: 67

Answers (2)

engineersmnky
engineersmnky

Reputation: 29478

If you are using nested_attributes you can do this

accepts_nested_attributes_for :user_groups, reject_if: lambda{|attr| attr[:id].blank?} 

I know you did not specify Rails in the question or the tags but the question still seems Railsy to me.

Upvotes: 0

usha
usha

Reputation: 29359

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"]}}

Upvotes: 2

Related Questions