Question: How to get all of the names from a specific Model

Question

How to get all of the names from a specific Model

Answers 1
Added at 2017-09-06 18:09
Tags
Question

I have a portfolio filtering for categories in order to show works from each category.

It works with a data-filter that triggers the works like this:

<span class="filter" data-filter=".<%= c.name.downcase.gsub(/[[:space:]]/, '') %>"><%= c.name %></span>

That works correctly for separate categories, but I want the :active tab to contain all of the works, so I need to get ALL of the category names:

<span class="filter active" data-filter="<%= Category.all.map(&:name) %>">Todos</span>

How can I retrieve the category names like "name1 name2 name3"...?

Thanks!

Answers to

How to get all of the names from a specific Model

nr: #1 dodano: 2017-09-06 18:09

If you want to get all the value of the name attribute for each category do this:

Category.pluck(:name) #=> ['name1', 'name2',..., 'name10']

From what you wrote you'd like the names to be spaced out like this "name1 name2 name3". Then just join the names with a space between each of them:

Category.pluck(:name).join(' ') #=> name1 name2 ... name10

@Stefan makes a valid point. It is considered bad practice to have logic such as Category.all in the view layer. Rather, you should put that logic in your controller action that is responsible for rendering the particular template (view).

i.e:

in controller

def works
 @category_names = Category.pluck(:name)
end

in view

<span class="filter active" data-filter="<%= @category_names.join(' ') %>">Todos</span>
Source Show
◀ Wstecz