フォロワーが多い順にユーザーを表示する方法を考えています。
まず、手順として下記のようなSQL文が吐き出されたらフォロワーが多い順に表示することができました。
sql
1SELECT * 2FROM users 3INNER JOIN ( 4 SELECT COUNT(relationships.following_id) 5 AS count_following_id, 6 following_id 7 AS following_id 8 FROM "relationships" 9 GROUP BY relationships.following_id 10) 11AS followranks ON users.id = followranks.following_id 12ORDER BY count_following_id DESC;
そこで、このSQLをどうやったらrailsで書けるかを調べてみました。
今回はModelに書かずにControllerに書くことにしました。
ruby
1relationships = Relationship.select("count('relationships.following_id') as count_following_id,following_id as following_id" ).group('following_id').arel 2 3@ranking_following = User.arel_table.join(relationships).order('count_following desc').to_sql
それから、viewに
ruby
1<% @ranking_following.each do |user| %> 2 <%= user.name%> 3<% end %>
と書いて実行したら、
undefined method `each' for #String:0x000000082f67c0
というエラーがでたのですが、この原因はなんでしょうか?
controllerに書いた文法が間違っていたのでしょうか?
それかそもそもやり方が間違っていたのでしょか?
ご存知の方がいらっしゃいましたら、ご教示ください。
よろしくお願いいたします!
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/09/28 04:56