views:

33

answers:

3

I really like this syntax, though I forgot what it was called

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

but I would like to do something similar for find

<% @managers = User.find{|x| x.isAdmin == true} %>

any ideas?

currently my solution tells me it can't find the object without an id, probably because I'm trying to treat active record like an array...

+3  A: 

You could use @managers = User.find_all_by_isAdmin(true) or @managers = User.find(:all, :conditions => ['isAdmin = ?', true]).

Edit: To really be like what you have above, it might be something more along the lines of User.all.select { |x| x.isAdmin == true } but that seems a little weird as you'd be fetching everything from the User table, when you don't need to.

theIV
Well, this is a has and belongs to many relationship, so isAdmin won't work in a SQL query?This is what I have.. currently doesn't work: <% @managers = User.find(:all, :conditions => ["account_id = ?", current_account]).select(|x| x.isAdmin? == true) %>
DerNalia
I'm a little confused. Which part is the habtm relationship? Do Users have and belong to many Managers? Can you do `current_account.managers.select { |x| x.isAdmin? }`? Is it a self reflecting association? As an aside, you actually don't need the `== true` part in the select because it will assume that you want the items who will return true values for the block. Maybe if you could update your question with a little more information about your specific case, we could provide you with a better answer.
theIV
+1  A: 

Since ActiveRecord is basically translating any find() requests into equivalent SQL queries, I think it would be difficult to ask it to translate an arbitrary condition stated in ruby code (x.isAdmin == true) into SQL.

So either you can use one of the more SQL-friendly approaches, such as User.find(:all, :conditions => 'isAdmin = true'), or you can pull everything from the database and then apply ruby-style filtering afterwards: User.find(:all).select(|x| x.isAdmin == true)

The latter approach is probably not a good idea in most cases, since all of the rows will have to be returned and then processed in-memory, but it can make sense where the selection criteria is complex and hard to translate into ActiveRecord queries or into SQL.

JacobM
Well, this is a has and belongs to many relationship, so isAdmin won't work in a SQL query?This is what I have.. currently doesn't work: <% @managers = User.find(:all, :conditions => ["account_id = ?", current_account]).select(|x| x.isAdmin? == true) %>
DerNalia
A: 

I don't think you should do this. As theIV said, it would be a lot better if you use something like

@managers = User.find_all_by_isAdmin(true)

There's no need to fetch everything from db if you won't use.

j.