Let me resolve this named scope to which you referenced above. Imagine a Question model in which there are many comments.
named_scope :most_active, :select => "questions.*", :joins => "left join comments as comments_for_count on comments_for_count.question.id = questions.id", :group => "questions.id", :order => "count(questions.id) desc" :most_active
scope name. You refer like this: Question.find (: all) .most_active
:select => "questions.*"
by default, scopes selects all the columns from your table anyway, so this limits the results to just the question table and not the comment table. It's not obligatory.
:joins => "left join comments as comments_for_count on comments_for_count.question.id = questions.id"
This speaks for every question, I also want to get all the comments related to them. There is a column "question_id" in the comments table, which we will use to match them with the corresponding question entry. It is important. This allows us to access fields that are not relevant to our model!
:group => "questions.id"
This is necessary for the count () function in the order clause to tell us that we want the number of comments based on the question. We do not need the count function in our order clause, so we also do not need this group instruction
:order => "count(questions.id) desc"
Return the results in order of number of comments, from highest to lowest.
So, for our example, discarding what we donโt need and applying it to your needs, we get:
:named_scope :by_program_manager_name, :joins => "left join users on projects.program_manager_id = users.id", :order => "users.name"
This named_scope will be called like this:
Project.find(:all).by_program_manager_name
Note that this is basically equivalent to:
Project.find(:all, :joins => "left join users on projects.program_manager_id = users.id", :order => "users.name")
But, as stated above, you should really know basic SQL. Your abilities will be very difficult without this understanding.