首页 > 解决方案 > 错误:在查询具有多个直通关系的表时,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')):

标签: sqlruby-on-railsrubysqliterails-activerecord

解决方案


默认情况下,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)')

推荐阅读