stevec
stevec

Reputation: 52268

How to extract grouped results from single model/table and provide to the view

I have a model called Language, with just two columns: language and link, and would like to be able to loop through each link for each language and display in the view. i.e. (obviously this isn't code, it's just to illustrate the desired pattern)

Language 1
   Link 1
   Link 2
   Link 3
Language 2
   Link 1
Language 3
   Link 1
   Link 2
Language 4
etc

What is the 'rails way' of extracting this data, and then presenting in the view? (note: I would know how to do this easily if the data were in two different models, but it isn't)

Upvotes: 2

Views: 21

Answers (1)

SRack
SRack

Reputation: 12203

So, a Railsy way would be to use the following in your controller:

@languages = Language.all.group_by(&:language)

This will give you a hash of languages grouped by the (erm...) language's language (<- perhaps rename the column to name to avoid this ambiguity?):

# { 'English' => [language_1, language_2, etc...],
#   'French' => [language_3, language_4],
#    etc... }

And then this in your view:

<% @languages.each do |language_name, languages| %>
  <h1>
    <%= language_name %>
  </h1>
  <% languages.each do |language| %>
    <p>
      <%= language.link %>
    </p>
  <% end %>
<% end %>

Obviously the HTML tags can be whatever you'd like, though I hope that gives a useful example.

However, there's a caveat here - as your database grows, this might not prove an efficient way of working. You'll likely be better off setting up a separate model for links, with a one-to-many relationship between languages and links.

For example:

# langage.rb
has_many :links

# link.rb
belongs_to :language

# your controller
@languages = Language.includes(:links)

And then something like the following in the view:

<% @languages.each do |language| %>
  <h1>
    <%= language.language %>
  </h1>
  <% language.links.each do |link| %>
    <p>
      <%= link.url %>
    </p>
  <% end %>
<% end %>

Upvotes: 3

Related Questions