0

Im new in rails and ruby! I have a database with records about articles. Each article has the following fields: - tittle - author - body

I would like to render in the index page a list of the count of ALL articles with the same "tittle" and the same "author". Example:

Database:

tittle: "dogs", author: "john", body: "dogs are nice",
tittle: "cats", author: "john", body: "cats are nice",
tittle: "dogs", author: "Lisa", body: "dogs are bad",
tittle: "dogs", author: "john", body: "dogs are nice",
tittle: "dogs", author: "john", body: "dogs are nice",
tittle: "dogs", author: "Lisa", body: "dogs are bad"

Now in my index page I would like to list in the occurrence desc order like this:

Articles:
  tittle  Author  how many times

- "dogs"  "john"      3 
- "dogs"  "Lisa"      2
- "cats"  "Lisa"      1

I was thinking about enumerable: 'group_by' , or a query Article.select([:id, :name]) ? however, I don't know how to apply it to my code.

Currently my controller looks like this:

  def index
    @articles = Article.order(created_at: :desc)
  end

I would really appreciate ideas or solutions on how to solve this as painless as possible and keep learning from this.

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Noname
  • 91
  • 3
  • 11

1 Answers1

0

Try this query:

@articles = Article.group(:tittle, :author).count

It will return you a hash like:

{ [tittle, author] => count, ... }

And you can iterate it like so:

@articles.each do |(tittle, author), count|
  ...
end

Also .order(created_at: :desc) part is redundant and I guess you have typo in tittle column name. I would rename it

Ref https://stackoverflow.com/a/2022424/4950680

Martin
  • 4,042
  • 2
  • 19
  • 29
  • You could also iterate via `each do |(title, author), count|` and skip that next line. – engineersmnky Jun 26 '19 at 14:07
  • @engineersmnky Good catch! Thanks – Martin Jun 26 '19 at 14:08
  • @MartinZinovsky you awesome! that seems to work. Can you add me in one more things please? the result now is : `{["dog", "John"]=>3}` how can I make it look nicer? I tried `.humanize` but that works on strings. any suggestion? and thanks I really appreciate your time and help!!! – Noname Jun 26 '19 at 16:50
  • @Noname What do you mean by nicer? – Martin Jun 26 '19 at 17:14
  • @MartinZinovsky hey! I mean instead of displaying ```{["dog", "John"]=>3}, {["cat", "Lisa"]=>1}``` with curly brackets and such, to displace it like this: ```"dog", "John" => 3 "cat", "Lisa" => 1 ``` More understandable for the readers and also with a break like between each. – Noname Jun 26 '19 at 17:24