user984621
user984621

Reputation: 48521

Rails - how to group/map records from database into a string?

I fetch data from database and they have this structure:

@articles = Article.where(...)

in @data:

id | author_id | article_name | ...
1  | 1         | Morning      | ...
2  | 1         | Wednesday    | ...
3  | 2         | Hallo!       | ...

When I need to find out how many articles does have an author, I do it this way:

<% articles = Hash[@articles.group_by(&:author_id).map {|k,v| [k,v.length]}] %>
<% @data.uniq_by {|x| x["author_id"]}.each do |result| %>
  <%= articles[result.author_id] %>

But I would need to also fetch similarly also article names and access to them the same way as to the count of articles. I would need something like this:

<%= articles2[result.author_id] %> # and this would print out "Morning,Wednesday" for the author with ID 1

Which method should I use for this?

Upvotes: 0

Views: 1637

Answers (2)

Doydle
Doydle

Reputation: 921

You could make the whole process a lot easier by using rails relations:

class Author < ActiveRecord::Base
  has_many :articles
end

Then you can iterate over all the authors and grab the information you want:

<% @authors.each do |author| %>

  # number of articles
  <%= author.articles.count %>

  # list of article names
  <%= author.articles.pluck(:name).join(', ') %>
<% end %>

Upvotes: 2

Santhosh
Santhosh

Reputation: 29174

This should work, not tested though

<% @articles.group_by(&:author_id).each do |id, articles| %>
  <%= articles.map(&:article_name).join(",") %> for author with ID: <%= id %>
<% end %>

Upvotes: 1

Related Questions