tmp delete from activerecord

Hello,

This is the case: A project has many users. a project has an admin.

when I list the project users I don't want to display the admin user so what I tried was:

users = @project.users users.delete(admin_user)

users.each { |u| { ... }

but what happens is that the admin_user gets deleted from the project. is there a way to do a temporary delete without activerecord acting upon it and without having to check with an 'if' inside the for loop?

thanks

in your table you must have an field, that defines the role of the user. either an bool flag like is_admin, that can be true or false or a integer or string, with several states like admin, customer and so on.

with a is_admin flag: users = @project.users.find_by_is_admin(false)

with an integer role (0=normal user, 1 = admin) users = @project.users.find_by_role(0)

with a string role ("admin" = admin, "user" = user...) users = @project.users.find_by_role("user")

Very strange, as this should work just fine. I too would expect this to perform an Array#delete, not an ActiveRecord::Base.delete, and testing this in one of my projects worked fine.

Can you verify that the result of @project.users is indeed an array?

Jan

hm, i see. you want to use the array delete function. i'm not sure, how you could get the "old" one that was overwritten by ActiveRecord.

maybe you could use delete_if, as far as i know that's not recycled by Rails.

users.delete_if {|u| u == admin_user }

but since it has to go through the whole array and check every single item, you could do it in the loop, as far as performance is concerned.

Hello Jan,

Thanks for the reply.

@project.users.class says it is an Array.

when I don't do the 'delete' then the admin user does not get removed so this shouldn't be a problem in another part of my code.

strange indeed

It's not an array, it's an association proxy.

u = @project.users u.delete(foo)

is the same as @projects.users.delete(foo) (indeed there would be some very funky going on if it wasn't).

In this case you could do something like users_without_admin = @project.users.reject {|u| u == admin} or of course arrange for admin not to be in @project.users in the first place.

Fred

Jiminy, I didn't know that. And of course I tested it with a regular finder, not with an association .. my bad.

Thanks Fred!

with a is_admin flag: users = @project.users.find_by_is_admin(false)

find_all_by_is_admin!