简体   繁体   中英

Ruby on Rails Join Table Associations

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.

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 => [ ... ])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM