1

When performing a search of shops and paginating the results (10 per page) on the left hand side of the page I need to show the list of employees (without duplicates) that work in all the shops currently displayed.

In the view I have the following but it doesn't feel like the most efficient and it shows duplicate employees

- @shops.each do |shop|
- shop.employees.each do |employee|
 %li = link_to "#{employee.name}", employee_path(employee)

3 Answers 3

2
@shops.map(&:employees).flatten.uniq.each do |employee|
  %li = link_to "#{employee.name}", employee_path(employee)
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! One more question, how can I arrange alphabetically by employee name?
2

uniq?

- @shops.each do |shop|
- shop.employees.uniq.each do |employee|
 %li = link_to "#{employee.name}", employee_path(employee)

Comments

0

This type of query should be done at the DB rather than in-memory.

class Shop
  has_many :employees
end

class Employee
  belongs_to :shop
end

Retrieve the employees for the given collection of shops in your controller:

@employees = Employee.all_by_shop_id(@shops, :order => :name)

Now in your view:

[email protected] do |employee|
  %li = link_to "#{employee.name}", employee_path(employee)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.