views:

189

answers:

2

Hey,

I have a Ruby on Rails application setup like so:

User Model

has_and_belongs_to_many :roles

Role Model

has_many :transactions
has_and_belongs_to_many :users

Transaction Model

belongs_to :role

This means that a join table is used called roles_users and it also means that a user can only see the transactions that have been assigned to them through roles, usage example:

user = User.find(1)
transactions = user.roles.first.transactions

This will return the transactions which are associated with the first role assigned to the user. If a user has 2 roles assigned to them, at the moment to get the transactions associated with the second role I would do:

transactions = user.roles.last.transactions

I am basically trying to figure out a way to setup an association so I can grab the user's transactions via something like this based on the roles defined in the association between the user and roles:

user = User.find(1)
transactions = user.transactions

I am not sure if this is possible? I hope you understand what I am trying to do.

A: 

You could add a method to User to collect the transactions for each of the user's roles into an Array of Arrays and then flatten this into a single Array:

class User < ActiveRecord::Base
  def transactions
    user.roles.collect { |role| role.transactions }.flatten
  end
end
mikej
+1  A: 

If you don't want to execute separate SQL queries to find transactions for each role, you can first get role_ids for the user, and then find all transactions with these role ids with single query:

class User < ActiveRecord::Base
  #...
  def transactions
    Transaction.scoped(:conditions => {:role_id => role_ids})
  end
end

Transaction.scoped is used here so you can add more conditions when necessary, like

user.transactions.all(:limit => 10, :conditions => [ ... ])
Voyta
Voyta's answer is better than mine. Also, see this blog post for more information on using `scoped`: http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality
mikej