Feature Request - Method to differentiate between a NullRelation and Actual Relation ?

Hey,

I am passing a relation to a method. When the relation has been called with the none method, I want to do something else than usual flow. This is what I have to detect the NullRelation:

> User.where(id: 1).extending_values.include?(ActiveRecord::NullRelation)
=> false

> User.where(id: 1).none.extending_values.include?(ActiveRecord::NullRelation)
=> true

Can we have a method on ActiveRecord::Base or any other suitable module, which can tell me if the relation is null without the above hack ?

Thanks,

Shadab

P.S. My first post in this email chain. Feel free to ridicule me if i broke any rules

That’s the only way right now.

Although, seems wrong to me check if a relation is a null relation, that’s the point of null objects, you should not know that’s a null object at all (may be necessary in your case but seems wrong to me).

What you can do is something like `relation.empty?’ which will return true in null relations, but note that “real” relations may return true if there is no records too :wink:

Hey,

I agree with Gabriel Sobrinho. This check goes against the point of having a NullRelation at all. Maybe you can provide more context about your use-case and why you need that check.

Ok let me give you more context:

def process_relation(relation)

return when relation.is_none?

do some more processing here since we know relation will return results and then return processed result

end

The problem is if I need to figure out whether a relation is none. For relations which are in-fact none, I can simply run a none? array method on them. But since any relation is passed to this method, if I run the method none? on a “non-none” relation then it executes the query since none? being array method. I only need to know if a relation being passed is a none relation without actually running a query.

But the thing is if you are passed a relation as method argument, how you check whether its a none relation ? It’s similar to checking nil on a method argument

Shadab, if I get you correctly you don’t want to do extra processing on an object if its NullRelation, based on the fact the default value for a result from
the relation would be 0/nil etc, ex: size would return 0.

I don’t think differentiating on the basis of this is a good idea, the basis of not processing some code should be one of the

methods you expect to return nil or zero.

Ex.

return if rel.empty?

<…process here>

Correct me if I am wrong with the example.

Having a distinguishing factor makes the NullRelation a secondary citizen, which defeats its purpose.