Reputation: 1695
I have a model with name Employee.rb I want to select all inside Employee table but the without repetition of employeeID for eg.
id emp_name employeeID shop_id
1 name1 13 4
2 name2 15 5
3 name3 16 4
4 name2 15 3
5 name2 15 4
6 name4 18 6
If this is the table structure i want to get an active record relation like this
#<ActiveRecord::Relation [#<Employee id: 1, emp_name: name1, employeeID: 13, shop_id: 4>, #<Employee id: 2, emp_name: name2, employeeID: 15, shop_id: 5>, #<Employee id: 3, emp_name: name3, employeeID: 16, shop_id: 4>, #<Employee id: 6, emp_name: name4, employeeID: 18, shop_id: 6>>
where the employeeID is unique. wont repeat
Is there any single line command to do this in Ruby on Rails.Pls help
Upvotes: 0
Views: 195
Reputation: 54684
Using Postgres you can do
Employee.select('DISTINCT ON (employeeID) *')
Upvotes: 2
Reputation: 3721
What so far I got is:
Employee.all.uniq_by(&:employee_id)
You can also use where clause:
Employee.where(name: 'name2').uniq_by(&:employee_id)
Upvotes: 2