タイトルわかりにくくてすみません。以下、具体的に書きます。
Userモデル
id | name | year | gender |
---|---|---|---|
1 | user1 | 2000 | male |
2 | user2 | 1985 | male |
3 | user3 | 1980 | female |
4 | user4 | 1985 | female |
5 | user5 | 1998 | male |
… | … | … | … |
こんな感じのデータから、indexページに以下のような表を作る場合。
year | 人数 |
---|---|
1980 | 10 |
1981 | 32 |
1982 | 21 |
1983 | 23 |
1984 | 44 |
1985 | 16 |
… | … |
プログラミング初心者だとこう考えてしまって、ものすごく非効率です。
users_controller.rb def index @count1980 = User.where(year: "1980") @count1981 = User.where(year: "1981") @count1982 = User.where(year: "1982") @count1983 = User.where(year: "1983") ・ ・ ・ end users/index.html.erb <table> … <td><%= @count1980.count %></td> <td><%= @count1981.count %></td> <td><%= @count1982.count %></td> …
そこで、浅い知識を総動員して、コントローラーで
@year = User.group(:year).pluck(:year).sort
とし、
users/index.html.erb
<table> <tr> <th>year</th> <th>人数</th> </tr> <% @year.each do |f| %> <tr> <td><%= f %></td> <td> </td> ←??? </tr> <% end %> </table>
こんな感じで書こうと思ったのですが、この場合どうやって各yearごとの人数をとればいいのでしょうか(上記コード内矢印←の箇所)。
あるいはもっと効率のいい方法がありましたら(きっとあるのでしょうが)教えてください。
ちなみにyearカラムはstringでなくtextで入れています。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/16 06:31