question about a where condition

Hey all,

This example of working code:

@a = @b.where(:a_group_id.ne => nil).collect { |b| b.a_group }

doesn't make too much sense to me. For one, I am not sure what that
"ne" is doing there. Is this a postgresql thing? Second, it looks like
we are collecting active record objects where the a_group_id is null,
collecting them in an array and then invoking the a_group association
method on it to get its association. That doesnt make sense because
the fact that we collected objects which had no association, how can
we invoke the association method on it?

thanks for response

John Merlino wrote in post #1021280:

Hey all,

This example of working code:

@a = @b.where(:a_group_id.ne => nil).collect { |b| b.a_group }

doesn't make too much sense to me. For one, I am not sure what that
"ne" is doing there. Is this a postgresql thing? Second, it looks like

The "ne" is Arel's version of "Not Equal." So that's ":a_group_id not
equal to nil"

we are collecting active record objects where the a_group_id is null,
collecting them in an array and then invoking the a_group association
method on it to get its association. That doesnt make sense because
the fact that we collected objects which had no association, how can
we invoke the association method on it?

@a will contain a collection of the associated objects for records where
the associated object exists (is not nil).

thanks for response. What you said explained a lot.

Now I have never seen rails code written like that. Would it have been
better to do this:

@b.map(&:a_group).compact.uniq

That would load up all of the elements -- whether they matched (not nil) or not, and then filter them, so it's kind of wasteful. Doing it all in Arel like that means that when the final SQL is compiled out of your Ruby method chain, the actual request to the DB will only return the resources you wanted, rather than also returning non-matching results.

Walter

Depends. What that does is pull back all the results and then
compact/uniq them in ruby -- whereas adding the where clause in the
first example limits the number of rows brought back from the
database.

If there are a lot of rows in the database (1000's or maybe even
millions of rows) this may be a substantial difference. If there are a
few hundred or less rows, it doesn't make that big of a difference.

But in general, I'd say that an approach that limits what's brought
back from the database is probably better.

Kevin Bedell
Boston Agile Partners
@kbedell

thanks for responses