AnApprentice
AnApprentice

Reputation: 110980

Given an Object from the database, how to remove a single item from the object?

I have a query like so:

@users = User.where(:something => 'met')

This returns back @users with 1+ items

What I want to do is loop through the @user object to see if a condition is met, if the condition is met I want to delete the item from the object. I've been trying the following but it does not appear to work though does not error.

@users.each_with_index do |u, index|
  @users.delete(index) if u.id == 12
end

Suggestions on a better way to make this work?

Thank you

Upvotes: 0

Views: 89

Answers (3)

rewritten
rewritten

Reputation: 16435

Do you want to delete it from the database or just from the list?

In the former case, do

@users.each do |u|
  u.delete if u.id == 12
end

In the latter, do

@users.reject! do |u|
  u.id == 12
end

or, if the condition is some method on user returning "true"/"false"-ish values,

@users.reject! &:is_12

class User < ActiveRecord::Base
  def is_12
    self.id == 12
  end
end

Upvotes: 3

tadman
tadman

Reputation: 211610

It's usually a better idea to exclude the record in question from your fetch:

@users = User.where(:something => 'met').where('id!=?', 12)

Otherwise you have to manipulate the result set. An easy way to do this is convert it to a Hash and delete the offending key(s):

@users = Hash[User.where(...).collect { |u| [ u.id, u ] }]
@users.delete(12)

Upvotes: 0

bricker
bricker

Reputation: 8941

Array#delete_if :

@users.delete_if { |u| u.id == 12 }

You can also exclude it from the query all together:

User.where(:something => "met").where("id != ?", 12)

The reason your try isn't working is because Array#delete takes an object, not an index. So you'd have to tweak your example:

@users.each { |u| @users.delete(u) if u.id == 12 }

But that seems silly given the delete_if method :)

Upvotes: 0

Related Questions