24

I have set of active record object in array.

I just want to delete on object from array not in database

a = Model.limit(2)

b = Model.first

a.delete(b)

returning nil value

Its not deleting

is there anyway?

3 Answers 3

29
a.to_a - [b]

Background: a.to_a convertrs the relation into an array in in memory.
[b] is an array whith just the element, you want to delete (in memory).
a.to_a - [b] does an array substraction.

(In Rails 3.2 .to_a was applied automatically to a relation when it was accessed. I agree with gregates: It's better to convert the relation to an array explicitly)

Sign up to request clarification or add additional context in comments.

Comments

15

There's potentially some confusion here because in ActiveRecord, Model.limit(2) does not return an array.

Model.limit(2).class #=> ActiveRecordRelation

So when you call a.delete(b), you may not be calling Array#delete.

Try this instead:

a = Model.limit(2).to_a # Executes the query and returns an array
b = Model.first
a.delete(b)

2 Comments

nice idea to use all to get an array out of the relation. I tried and to_a works as well and might be a fraction more explicit.
all does not return an array anymore in Rails 4.2, to_a does.
4

This is what you need:

objects_in_db = Model.all
objects_in_array = Model.first(2)
objects_in_array.delete_if { |obj| !objects_in_db.include?(obj)}

In your case, Model.limit(2) may not return the first two object and so the array a may not contain b and hence, it returns nil.

2 Comments

i can see the matching object is avail in b
can you provide your model's structure?. Try with some other model and see if there is any problem with your model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.