3

Is there some sort of short hand for

  @notifications = Notification.find(:all, :conditions => ['expires_at > ?', Time.now])

  notif = Notification.find(:all, cookie[0].to_i)
  @notifications.delete(notif[0]) if not notif.empty?

cookie is an id of a notification stored into cookies. this is in an iteration, that removes notifications that the user doesn't want to see.

thanks! =)

2 Answers 2

8

If this is an array of activerecord objects, you could delete from the database like this.

Notification.delete_all(:id => cookie[0].to_i)

If this is just an array, then you can use the delete if

@notifications.delete_if{|x| x == cookie[0].to_i}

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

3 Comments

an array has no method, delete_all. =\
is this an array of activerecord objects? and if so, so you want to delete just from the array or delete from the database? I added a one-liner to delete from an array. Not totally sure what @notifications is now.
close, @notifications.delete_if{|x| x.id == cookie[0].to_i} did the trick. thanks for helping!
1

Now you could just use the delete_at( index ) method:

array = ['item0', 'item1', 2, 3]
array.delete_at 1
# => "item1" 
array.delete_at 2
# => 3
array
# => ["item0", 3] 

You could do the same with slice!( index ).

Note: delete_at is a mutator method even if it doesn't end in !, so don't rely on its return value, it will only be the deleted item.

Reference: http://ruby-doc.org/core-2.2.0/Array.html#method-i-delete_at

Comments

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.