0

I've got a loop that looks like this:

<% current_user.brand.templates.each do |template| %>
  <li><%= link_to(template.label, new_templated_document_path(template)) %></li>
<% end %>

A Template can have a category, but it's just a string and not an association. Is there a way to collect the Templates here based on category and sub-menu them accordingly? It feels like I'll have to build an array for each category in the model or something. Something like this:

categories = []
Template.categories.each do |c|
  category = []
  category << Template.where(category: c).all
  categories << category
end
categories

Feels pretty clumsy though. Any help?

Update

I've changed it to this:

@categories = {}
Template.first.categories.each do |c|
  @categories[c] = current_user.brand.templates.where(category: c)
end

But I can't seem to get the records into the hash. Is that even possible?

t56k
  • 6,769
  • 9
  • 52
  • 115

2 Answers2

2

According to this you can use something like Template.where(category: Template.categories). You can also take a look here where it is stated that:

Client.where(orders_count: [1,3,5])

will produce

SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))

Which I think is what you want.

Community
  • 1
  • 1
Ivaylo Petrov
  • 1,162
  • 9
  • 18
1

I think you can query the templates and group them by category, that would be much more easier

Template.all.group_by(&:category)

You will get a hash with key is the category and values are lists of templates

The Lazy Log
  • 3,564
  • 2
  • 20
  • 27