在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?

查看:152
本文介绍了在Ruby中,用ActiveRecord的是检索belongs_to的父对象的对象最好的方式,给予一定的条件呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中的组织 的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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆