I use Rails 4. I have an application where i have a many-to-many relationship :
class User < ActiveRecord::Base
has_many :relationshipfollows, :foreign_key => "follower_id",
:dependent => :destroy
has_many :following, :through => :relationshipfollows, :source => :followed
end
class Project < ActiveRecord::Base
has_many :relationshipfollows, :foreign_key => "followed_id",
:dependent => :destroy
has_many :followers, :through => :relationshipfollows, :source => :follower
end
class Relationshipfollow < ActiveRecord::Base
belongs_to :follower, :class_name => "User"
belongs_to :followed, :class_name => "Project"
end
I follow this tutorial : http://ruby.railstutorial.org/chapters/following-users?version=3.0#top
But now I'd like to list all projects ordered by the number of follower. Like this :
1. project1 | 99 followers
2. project2 | 16 followers
3. project3 | 2 followers
...
I'm new to rails and I guess I keep making a mistake because I try a lot of examples like this : Rails 3 Order By Count on has_many :through or has_many , through: relationship count
I try this method :
Project.joins(:relationshipfollows).group("relationshipfollows.project_id").order("count(relationshipfollows.project_id) desc")
But i have this error : SQLite3::SQLException: no such column: relationshipfollows.project_id: SELECT "projects".* FROM "projects" INNER JOIN "relationshipfollows" ON "relationshipfollows"."followed_id" = "projects"."id" GROUP BY relationshipfollows.project_id ORDER BY count(relationshipfollows.project_id) desc
And I try a another method :
Project.joins(:relationshipfollow).select('following.*, COUNT(followers.id) AS user_count').group('project_id').order('COUNT(followers.id) DESC')
But I have this error : Association named 'relationshipfollow' was not found on Project; perhaps you misspelled it?
Could someone please help me to find the right direction how to make it all work ?
Cordially
Edit : I think the problem its from here. When I try this :
Relationshipfollow.select(:followed_id, "COUNT(follower_id) AS total").group(:followed_id).order("total DESC")
he return me this :
=> # ActiveRecord::Relation [# Relationshipfollow id: nil, followed_id: 2, # Relationshipfollow id: nil, followed_id: 1, # Relationshipfollow id: nil, followed_id: 3]
All projects are ordered by the number of followers and all followed_id (projects) are in the good order in relative of my test. But when I join this to my model Project like this :
Project.joins(:relationshipfollows).select(:followed_id, "COUNT(follower_id) AS total").group(:followed_id).order("total DESC")
he return me a list of projects but with project_id NULL :
=> #ActiveRecord::Relation [# Project id: nil, # Project id: nil, # Project id: nil]