【问题标题】:A body which lists the Artists with the most songs in order按顺序列出歌曲最多的艺术家的正文
【发布时间】:2017-11-29 22:44:32
【问题描述】:

我创建了一个 ruby​​ on rails 程序,它由两个数据库组成

父表

CreateArtists < ActiveRecord::Migration
   def change
    create_table :artists do |t|
    t.string :name, null: false
    t.integer :age, null: false

    t.string :nationality, null: false

    t.timestamps null: false
   end
  end
end

子表

CreateSingles < ActiveRecord::Migration
    def change
     create_table :singles do |t|
     t.belongs_to :artist, index: true, foreign_key: true
     t.string :title, null: false
     t.integer :year, null: false

     t.timestamps null: false
     end
   end
  end`

目前我正在显示艺术家,但希望他们按歌曲最多的降序排列

<thead>
<tr>
  <th>Name</th>
  <th>Age</th>
  <th>Nationality</th>
</tr>
</thead>

<tbody>
 <% @artists.each do |artist| %>
  <tr>
    <td><%= artist.name %></td>
    <td><%= artist.age %></td>
    <td><%= artist.nationality %></td>
  </tr>
<% end %>
</tbody>
</table>

我知道我可以使用计数器缓存来确定哪个艺术家的歌曲最多,但我想使用查询

我知道我需要改变

@artists.each do |artist|

有什么想法吗?

这也是我第一次在堆栈溢出上发帖,所以为布局道歉

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你可以试试:

    Artist.joins(:singles)
          .group(:id)
          .order('count(artists.id) DESC')
    

    【讨论】:

    • 我有,但没有“计数部分”,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    相关资源
    最近更新 更多