【发布时间】:2015-12-07 18:46:24
【问题描述】:
更新
我正在使用 Spotify api 根据用户在我的网站上关注的艺术家来获取相关艺术家的信息。我想知道,如何对收到的响应进行排序,以便以某种方式显示内容。
对于在我的网站上关注的每个艺术家,我想按关注者总数从高到低对相关艺术家的响应进行排序。如果我网站上的用户关注超过 1 位艺术家,我希望相关艺术家信息的全部响应按关注者总数排序。例如,如果我网站上的某个人关注 Metallica 和 Oasis,我希望 Metallica 和 Oasis 的相关艺术家按追随者总数排序。现在,如果用户只关注一位艺术家,我的代码只能按照我想要的方式正常工作。
我该怎么做呢?我也不希望在我的回复中有任何重复的艺术家,因为有时某些艺术家会有相同的相关艺术家。
在我的网站上关注 2 位艺术家(Metallica 和 Oasis)时,我收到了相关艺术家的回复。必须把它放在一个要点中,因为这里发布的响应很大。
https://gist.github.com/jlquaccia/07998975d3f11324ab0d
控制器 - users_controller.rb:
def show
@user = User.find(params[:id])
@hash_version_array = []
@user.follows.each do |follow|
response = HTTParty.get("https://api.spotify.com/v1/artists/#{follow.artist_id}/related-artists")
@hash_version = JSON.parse(response.body)
@artist_name = follow.artist_name
@hash_version_array << @hash_version
end
sorted = @hash_version_array.first["artists"].sort_by { |a| a["followers"]["total"] }
@most_to_least_followers_version_array = sorted.reverse
end
查看 - users/show.html.erb:
<div class="row">
<div class="col-md-12 text-center">
<h3>Recommendations</h3>
<% if current_user.follows.count == 0 %>
<p>Recommendations based on who you follow will appear here..</p>
<% else %>
<p>Based on your follows you might also like..</p>
<% @most_to_least_followers_version_array.each do |item| %>
<div class="artist_recommendation_wrapper">
<div class="artist_recommendation artist_name newsfeed_artist">
<%= item['name'] %>
</div>
<%= number_with_delimiter(item['followers']['total'], delimiter: ',') %> followers
<%= link_to(image_tag(item['images'][0]['url'], class: 'img-responsive artist_recommendation_img', width: 200, height: 200), artists_path) rescue image_tag("microphone.png", class: 'img-responsive artist_img mic_bg', width: 200, height: 200) %>
<br>
</div>
<% end %>
<% end %>
</div>
</div>
【问题讨论】:
标签: ruby-on-rails spotify