Gustavo
Gustavo

Reputation: 235

Filtering a nested array based on Model

I have an nested array and want to remove the entries that matches the info on my model.

My array looks roughly like this:

[{"id"=>"72157627540544488", "primary"=>"6090588224", "photos"=>"49", "videos"=>0, "title"=>"Title1", "description"=>""},
{"id"=>"72157627309708150", "primary"=>"5987891163", "photos"=>"49", "videos"=>0, "title"=>"Title2", "description"=>""},
{"id"=>"72157626646787712", "primary"=>"5687687064", "photos"=>"11", "videos"=>0, "title"=>"Title3", "description"=>""},
{"id"=>"72157626646672290", "primary"=>"5687629990", "photos"=>"33", "videos"=>0, "title"=>"Title4", "description"=>""}] 

And my model:

id               :integer         not null, primary key
name             :string(255)
set_id           :integer
thumb_url        :string(255)
created_at       :datetime
updated_at       :datetime

What I'm trying to accomplish is to remove from the array all the elements where the value of id is duplicated in any of the set_id in my model.

Upvotes: 1

Views: 215

Answers (1)

aubreyrhodes
aubreyrhodes

Reputation: 787

You can do something like:

array.reject{|element| Model.exists?(:set_id => element['id'])}

where array is the array and Model is the model class. This will return a new array with the elements with duplicate id's removed.

Array.reject returns a copy of the array without the elements where the block passed in returns true.

ActiveRecord.exists? returns true if a model exists in the database with the given conditions.

Upvotes: 1

Related Questions