matiss matiss - 1 month ago 7
Ruby Question

Rails 5: distinct values in view

I have working solution where users who belong to current_user companies can be found.

In /controllers/users_controller.rb I have this:

def index
@companies = current_user.companies.includes(:users)
@users = @companies.map(&:users).flatten
end


In console I can get this (current_user ID=2):

User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
Company Load (0.2ms) SELECT "companies".* FROM "companies" INNER JOIN "accounts" ON "companies"."id" = "accounts"."company_id" WHERE "accounts"."user_id" = ? [["user_id", 2]]
Account Load (0.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."company_id" IN (14, 15, 16)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (1, 2)


Users: 1, 2 is my desired result.

/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


In view at the moment I have this:
<%= render @users %>
with this related partial:

<li>
<%= link_to user.name, user %>
</li>


How to get unique values of users? At the moment I get multiple values of users if one user is in several companies.

Answer

@users = @companies.map(&:users).flatten.uniq should do I believe

Also building on @idej's answer you could also do

@users = User.joins(:accounts).where("accounts.company_id IN (?)", current_user.companies.pluck(:id)).uniq 

which should do the same thing and be more efficient

Comments