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)

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

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:

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)


class Account < ActiveRecord::Base
belongs_to :user

class Transfer < ActiveRecord::Base
belongs_to :source, :class_name => “Account”
belongs_to :target, :class_name => “Account”

Environment: Rails 3.0.4 / Ruby 1.9.2

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs