【问题标题】:Rails 5: find all Users who belong to Companies, which belong to current_userRails 5:查找属于公司的所有用户,属于current_user
【发布时间】:2016-09-24 06:01:21
【问题描述】:

在我的应用中,用户可以拥有许多公司,反之亦然。在 Accounts 表中存储用户的 ID 和其公司的 ID。 我想找到属于公司的所有用户,属于 current_user。 假设 current_user 就像这些公司的主用户(不是管理员,因为那将是系统管理员)。 我该怎么做呢?我的猜测是用 Arel 来做,但是它在模型、控制器、视图中应该是什么样子?非常感谢您的帮助。我在 Rails 5 上。

models/user.rb

class User < ApplicationRecord
has_many :accounts, dependent: :destroy
has_many :companies, through: :accounts

models/account.rb

class Account < ApplicationRecord
belongs_to :company
belongs_to :user
accepts_nested_attributes_for :company, :user

models/company.rb

class Company < ApplicationRecord
has_many :accounts, dependent: :destroy
has_many :users, through: :accounts
accepts_nested_attributes_for :accounts, :users

我的 schema.rb 看起来像这样:

create_table "accounts", force: :cascade do |t|
t.integer  "company_id"
t.integer  "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["company_id"], name: "index_accounts_on_company_id"
t.index ["user_id"], name: "index_accounts_on_user_id"
end

  create_table "companies", force: :cascade do |t|
t.string   "name"
t.string   "legal_name"
t.string   "reg_number"
t.string   "address"
t.string   "bank_acc"
t.string   "description"
t.string   "website"
t.datetime "created_at",              null: false
t.datetime "updated_at",              null: false
t.integer  "role",        default: 0
t.integer  "currency",    default: 0
end

  create_table "users", force: :cascade do |t|
t.string   "name"
t.string   "email"
t.datetime "created_at",                      null: false
t.datetime "updated_at",                      null: false
t.string   "password_digest"
t.string   "remember_digest"
t.boolean  "admin",           default: false
t.index ["email"], name: "index_users_on_email", unique: true
end

【问题讨论】:

    标签: ruby-on-rails ruby arel


    【解决方案1】:

    您可以找到当前用户所在的公司,并急切加载属于这些公司的用户

    @companies = current_user.companies.includes(:users)
    

    要列出所有用户(可能在视图中),请遍历@companies 及其所有users

    @companies.each do |company|
      company.users.each do |user|
        puts user.name
      end
    end
    

    或者使用 map/collect 将它们分配给一个变量。

    @users = @companies.map(&:users).flatten
    

    【讨论】:

    • 工作顺利,我需要 :) 谢谢你的解决方案! Rails 社区最棒!
    • @Santhosh 关于视图,如何仅显示唯一的用户名?如果我有两家公司并且用户都在其中,那么用户名将显示 2 次。
    猜你喜欢
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2020-05-22
    • 2017-01-13
    相关资源
    最近更新 更多