Reputation: 7011
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?
Upvotes: 0
Views: 43
Reputation: 3574
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
Upvotes: 1
Reputation: 1172
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.
Upvotes: 2