在Ruby中,用ActiveRecord的是检索belongs_to的父对象的对象最好的方式,给予一定的条件呢? [英] In Ruby, with ActiveRecord what is the best way to retrieve an object that belongs_to a parent object, given some conditions?
问题描述
在我的模型中的组织
的has_many:用户
和用户
has_and_belongs_to_many:角色
和角色
有一个名称
和 has_and_belongs_to_many:用户
In my model an Organisation
has_many :users
, and a User
has_and_belongs_to_many :roles
and a Role
has a name
and has_and_belongs_to_many :users
.
在我的组织
类我有一个方法 get_admin
是应该获得用户
属于该组织
谁的角色
管理
。像这样:
In my Organisation
class I have a method get_admin
that is supposed to get the User
belonging to that Organisation
who has the Role
'admin'
. Like so:
def get_admin
return self.users.with_role('admin')
end
唉!这会返回一个的ActiveRecord ::关联
对象,而不是用户
。
我想追加。首先
来,像这样的行的末尾
I tried appending .first
to the end of the line like so
def get_admin
return self.users.with_role('admin').first
end
但后来我得到的是一个SQL错误
But then all I get is an SQL error
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: role.name: SELECT "users".* FROM "users" WHERE ("users".organisation_id = 2) AND (role.name == 'admin') LIMIT 1
我的架构正是如此定义的:
My schema is defined thusly:
create_table "roles", :force => true do |t|
t.string "name", :null => false
end
create_table "users", :force => true do |t|
t.string "username", :null => false
t.integer "organisation_id"
end
create_table "roles_users", :id => false, :force => true do |t|
t.integer "user_id"
t.integer "role_id"
end
create_table "organisations", :force => true do |t|
t.string "name", :null => false
t.string "website", :null => false
end
我将如何改写组织
的 get_admin
方法(如下)返回一个实际的用户
?
How would I rewrite the Organisation
's get_admin
method (as follows) to return an actual User
?
def get_admin
return self.users.with_role('admin')
end
干杯
戴夫
推荐答案
在用户模型中创建一个名为admin范围
Create a scope called admin in Users model
user.rb:
scope :admin, joins(:role).where('roles.name = ?', 'admin')
而get_admin方法应该是
And the get_admin method should be
def get_admin
return self.users.admin.first
end
这篇关于在Ruby中,用ActiveRecord的是检索belongs_to的父对象的对象最好的方式,给予一定的条件呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!