Ruby on Rails Join Table Associations

守給你的承諾、 提交于 2019-12-11 09:33:42

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2802539/ruby-on-rails-join-table-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!