如何找到基于一个多到很多相关的模型的属性记录? [英] How do I find records based on attributes of a many-to-many-related model?
问题描述
模型......
InternalUser
的has_many:internal_user_roles
的has_many:角色:通过=> :internal_user_roles
InternalUserRole
belongs_to的:internal_user
belongs_to的:角色
角色
的has_many:internal_user_roles
的has_many:internal_users,:通过=> :internal_user_roles
使用新的ActiveRecord的查询API,我怎么会找到所有的 InternalUser
s的管理员的角色?
在换句话说,我怎么产生这个查询...
SELECT
*
从
internal_users我,internal_user_roles IR,角色 - [R
哪里
i.id = ir.internal_user_id
和
r.id = ir.internal_user_id
和
r.name =管理
在理想情况下,你应该从一个对象,是管理角色:
角色= Role.find_by_name(管理)
然后,你可以简单地查询内部用户该角色:
role.internal_users
如果你想走得更远,你应该注意到,在ActiveRecord的所有关联可以根据进一步查询:
role.internal_users.where(:FIRST_NAME =>条例)。限制(5)
再回到原来的问题,或者你可以查询InternalUser模式:
InternalUser.includes(:角色)。凡(['?roles.id =',作用])
或许有点快,但更复杂的code-明智的:
InternalUser.includes(:internal_user_roles)。凡(['?internal_user_roles.role_id =',作用])
要直接转化你的SQL查询,你也可以做到这一点:
InternalUser.includes(:角色)。凡(roles.name ='管理员')
您还可以看到的SQL的ActiveRecord会产生(任何这些查询)通过把to_sql通话结束时,像这样:
InternalUser.includes(:角色)。。凡(roles.name =管理)to_sql
Models...
InternalUser
has_many :internal_user_roles
has_many :roles, :through => :internal_user_roles
InternalUserRole
belongs_to :internal_user
belongs_to :role
Role
has_many :internal_user_roles
has_many :internal_users, :through => :internal_user_roles
Using the new ActiveRecord query API, how would I find all the InternalUser
s with the "ADMIN" role?
In other words, how do I generate this query...
SELECT
*
FROM
internal_users i, internal_user_roles ir, roles r
WHERE
i.id = ir.internal_user_id
AND
r.id = ir.internal_user_id
AND
r.name = 'ADMIN'
Ideally you should start with an object that was the admin role:
role = Role.find_by_name('ADMIN')
Then you could simply query the internal users for that role:
role.internal_users
If you want to go further, you should note that all associations in ActiveRecord can be further queried upon:
role.internal_users.where(:first_name => 'Bill').limit(5)
Getting back to the original question, alternatively you could query the InternalUser model:
InternalUser.includes(:roles).where(['roles.id = ?', role])
or perhaps a bit faster, but more complex code-wise:
InternalUser.includes(:internal_user_roles).where(['internal_user_roles.role_id = ?', role])
To translate your SQL query directly, you could also do this:
InternalUser.includes(:roles).where("roles.name = 'ADMIN'")
You can also see the SQL that ActiveRecord would generate (for any of these queries) by putting a 'to_sql' call at the end, like so:
InternalUser.includes(:roles).where("roles.name = 'ADMIN'").to_sql
这篇关于如何找到基于一个多到很多相关的模型的属性记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!