2
我試圖從我的連接表「會員」中選擇所有的管理員用戶。我只需要選擇成員身份的所有用戶,其中組ID是x,成員角色是admin。SQLException:沒有很多通過加入這樣的列
@admins = User.joins(:memberships).where(["memberships.group_id ? and memberships.role ?", @group.id, "admin"])
問題是,不是試圖查看memberships.role,而是說沒有像users.role這樣的東西。我如何得到這個來尋找成員角色?
SQLite3::SQLException: no such column: users.role: SELECT COUNT(*) FROM "users" INNER JOIN "memberships" ON "users"."id" = "memberships"."user_id" WHERE "memberships"."group_id" = ? AND "users"."role" = ?
成員表中的模式:
create_table "memberships", force: :cascade do |t|
t.integer "group_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "role", default: 0
t.index ["group_id", "user_id"], name: "index_memberships_on_group_id_and_user_id", unique: true
t.index ["group_id"], name: "index_memberships_on_group_id"
t.index ["user_id"], name: "index_memberships_on_user_id"
end
membership.rb
class Membership < ApplicationRecord
enum role: { member: 0, admin: 1 }
belongs_to :user
belongs_to :group
validates :user_id, presence: true
validates :group_id, presence: true
end
group.rb
class Group < ApplicationRecord
belongs_to :creator, class_name: "User"
has_many :memberships, dependent: :destroy
has_many :users, through: :memberships
user.rb
class User < ApplicationRecord
has_many :created_groups, class_name: "Group"
has_many :memberships, dependent: :destroy
has_many :groups, through: :memberships
我看到一個'COUNT'在'SQL'查詢,但在'ActiveRecord'查詢表明沒有'count'。這是正確的查詢嗎? – Pavan
是的,這是來自控制器的確切查詢。 – ddonche
在查詢中有些東西是不正確的。試試這個@admins = User.joins(:memberships)。其中([「memberships.group_id =?和memberships.role =?」,@ group.id,「admin」])' – Pavan