sql - 错误:在查询具有多个直通关系的表时,rails
问题描述
我正在尝试弹出一个模式,它应该显示具有角色“玩家”的用户,我实现了三个表用户角色和用户角色,其中用户和角色具有许多通过用户角色表的关联。
条件如下一个用户可以是玩家或管理员或两者兼而有之,在显示时我们应该显示具有角色的用户,仅限玩家。
图式
create_table "roles", force: :cascade do |t|
t.string "name"
t.boolean "active"
t.integer "counter"
end
create_table "user_roles", force: :cascade do |t|
t.integer "role_id"
t.integer "user_id"
t.index ["role_id"], name: "index_user_roles_on_role_id"
t.index ["user_id"], name: "index_user_roles_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["team_id"], name: "index_users_on_team_id"
end
表模型如下
class User < ApplicationRecord
has_many :user_roles
has_many :roles, through: :user_roles, :dependent => :destroy
end
class UserRole < ApplicationRecord
belongs_to :role
belongs_to :user
validates :user_id, :uniqueness => { :scope => :role_id }
end
class Role < ApplicationRecord
has_many :user_roles
has_many :users, through: :user_roles ,:dependent => :destroy
end
在团队控制器中我有
def load_users
@user = User.includes(:userroles).where('userroles.name = ?',"Player")
respond_to do |format|
format.html
format.js
format.json
end
end
日志显示以下错误
错误(SQLite3::SQLException: 没有这样的列:userroles.name: SELECT "users".* FROM "users" WHERE (userroles.name = 'Player')):
解决方案
默认情况下,includes
不执行left join
而是执行两个单独的数据库查询。不过,您可以轻松强制left join
,在这种情况下,这样做就足够了:
@user = User.includes(:user_roles).where(user_roles: { name: 'Player' })
通过使用user_roles: { }
符号,您可以让 ActiveRecord 知道您还想按user_roles
列查询 DB,而 ActiveRecord 决定执行left join
。如果您没有可轻松转换为此表示法的条件,则可以强制left join
使用eager_load
:
@user = User.eager_load(:user_roles).where('some complex SQL query including user_roles column(s)')
推荐阅读
- python - Python:用项目列表替换列表中的项目
- git - 修剪来自 GitHub fork 的悬空提交
- html - Html, css 水平和垂直分离器
- prolog - 未定义的过程 DWIM 无法更正 Prolog 中的目标
- python - 使用 enumerate() 时出现“ValueError:需要超过 2 个值才能解压”
- twitter-bootstrap - dc js 选择菜单和带有引导程序的样式
- android - RxJava2 onSubscribe 和 onComplete
- mysql - 如何在 Laravel 5.2 中获取最新情况后的行号?
- go - Go 无法从字符串创建全局字节切片
- javascript - 我的单元测试配置有几个问题