简体   繁体   中英

Ruby on Rails : Find all departmentid from Users Table

I have Users Table which contains many fields including departmentid. departmentid is just a string . Each departmentid can have different users.Is it possible to find all departmentid from Users table without repetation.

I tried to find all departmentid from users table ,but the result contains duplication of departmentid.How to solve this .

Thanks in advance...

SQL

select distinct department_id from users

Ruby code

User.all.map(&:department_id).compact.uniq

also in rails 3

User.select('departement_id').uniq

You probably want to use a sql query to let the db engine to handle the math and avoid creating ruby objects, its the faster option:

Department.where("id in (select distinct department_id from users)").all

Now if you want to do it the rails way, you can still do:

Department.where(id: User.select("distinct department_id").map(&:department_id)).all

Notice that with this last line of code, you avoid creating a complete mapping of the User attributes, since all you are interested in is the department_id, and also it avoids going though every User object in order to collect the ids and make them uniq, by using select distinct the database engine will just return the single values without repetition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM