Arel: misunderstanding with intersections


I've been playing with Arel for a few days, but I feel really confused about predicates / arrays intersection.

Let's say I have 3 models: users, (bank) accounts and transfers. An account belongs to a user, and a transfer is made of a source and target accounts (see the snippets below).

Given a user, I want to query his transfers. I can go this way in the User class:

def transfers     Transfer.joins(:source) & Account.where(:user_id => id) end

Here, I intersect the sources accounts of all the transfers with the user's accounts. Having said that (as always wanting more and more conciseness), I wonder why the following is not working:

def transfers     Transfer.joins(:source) & accounts end

where 'accounts' is the user's accounts dependency.

To me, "Account.where(:user_id => id)" and "accounts" represent exactly the same concept. Is it because "Account.where(:user_id => id)" is a predicate and "accounts" is an Active Record association, so they aren't homogeneous?

Actually, "Transfer.joins(:source) & accounts" doesn't return anything (there is no error though), while "Transfer.joins(:source) & Account.where(:user_id => id)" works like a charm.

Can someone clarify this for me?

Thanks in advance for your help :slight_smile:

Here are the snippets:

[models/user.rb] class User < ActiveRecord::Base     has_many :accounts, :dependent => :destroy

    def transfers       # Useless to join the targets, since source and target necessarily belong to this user       # Why this doesn't work ? Transfer.joins(:source) & accounts       Transfer.joins(:source) & Account.where(:user_id => id)     end


[models/account.rb] class Account < ActiveRecord::Base     belongs_to :user end

[models/transfer.rb] class Transfer < ActiveRecord::Base     belongs_to :source, :class_name => "Account"     belongs_to :target, :class_name => "Account" end

Environment: Rails 3.0.4 / Ruby 1.9.2