SQLException:没有这样的列有很多通过连接

时间:2017-07-01 17:01:33

标签: ruby-on-rails

我试图从我的联接表中选择所有管理员用户"会员资格"。我只需要从成员资格中选择所有用户,其中组ID为x,成员角色为admin。

@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

1 个答案:

答案 0 :(得分:0)

你尝试过吗?如果你已正确定义has_many和belongs_to它应该工作,也许这是最简单的解决方案

User.memberships.where(group_id: @group.id, role: "admin")