Ruby on Rails merge into table associations

I have a Ruby on Rails application setup:

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 connection table is used called roles_users

, and also means that the user can only see transactions that have been assigned to them through roles, example of use:

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

      

This will return transactions associated with the first role assigned to the user. If a user has two roles assigned to them at this point in order to receive transactions associated with the second role, I will do:

transactions = user.roles.last.transactions

      

I'm basically trying to figure out a way to set up an association so that I can capture user transactions through something like this based on the roles defined in the association between the user and the roles:

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

      

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

+1


a source to share


2 answers


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

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

      



Transaction.scoped

used here to add additional conditions as needed, for example

user.transactions.all(:limit => 10, :conditions => [ ... ])

      

+1


a source


You can add a method User

to collect transactions for each of the user roles into an array of arrays, and then flatten that into one array:



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

      

0


a source







All Articles