Ruby on Rails Join Table Associations
Posted
by Eef
on Stack Overflow
See other posts from Stack Overflow
or by Eef
Published on 2010-05-10T12:25:33Z
Indexed on
2010/05/10
12:34 UTC
Read the original article
Hit count: 323
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.
© Stack Overflow or respective owner