Ruby on Rails的连接表关联 [英] Ruby on Rails Join Table Associations
问题描述
我有一个Ruby on Rails应用程序设置像这样:
I have a Ruby on Rails application setup like so:
用户模型
has_and_belongs_to_many :roles
角色模型
has_many :transactions
has_and_belongs_to_many :users
事务模型
belongs_to :role
这意味着连接表是用于一个名为 roles_users
,这也意味着用户只能看到已经通过角色被分配给他们的交易,使用示例:
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
这将返回它们与分配给用户的第一角色相关联的事务。如果用户有分配给他们,此刻2角色获得与我会做第二角色相关联的交易:
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.
推荐答案
如果您不想执行单独的SQL查询来找到每个角色交易,你可以先拿到role_ids用户,然后找到所有交易这些角色ID单查询:
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
用在这里,因此您可以在必要时添加更多的条件,如
Transaction.scoped
is used here so you can add more conditions when necessary, like
user.transactions.all(:limit => 10, :conditions => [ ... ])
这篇关于Ruby on Rails的连接表关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!