Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting a Rails database table by a column in an associated model
    primarykey
    data
    text
    <p>I'm trying to implement Ryan Bates' sortable table columns code (Railscast #228) but I'd like to be able to sort on an associated column. In particular, I have the following models and associations:</p> <pre><code>class Project &lt; ActiveRecord::Base belongs_to :program_manager, :class_name =&gt; "User" class User &lt; ActiveRecord::Base has_many :program_manager_projects, :class_name =&gt; "Project", :foreign_key =&gt; "program_manager_id" </code></pre> <p>The association between the Project model and the User model is mediated by the 'program_manager_id' foreign key, which the user sets in the new/edit views using a collection-select dropdown. Here's part of the annotation at the top of project.rb:</p> <pre><code># Table name: projects # program_manager_id :integer </code></pre> <p>I want to be able to sort my list of projects in the index view by the program manager's name, i.e., by project.program_manager.name.</p> <p>Ideally, I'd be able to point :order to this name somehow, perhaps with something like this in the index method of my ProjectsController:</p> <pre><code>@projects = Project.find(:all, :order =&gt; project.program_manager.name) </code></pre> <p>But that obviously won't work (not to mention Ryan's routine implements this with a specific reference to table names from the model to be sorted.)</p> <p>I've come across some intimidating approaches that use named_scope, such as:</p> <pre><code>named_scope :most_active, :select =&gt; "questions.*", :joins =&gt; "left join comments as comments_for_count on comments_for_count.question.id = questions.id", :group =&gt; "questions.id", :order =&gt; "count(questions.id) desc" </code></pre> <p>But given my lack of MySQL expertise, this is fairly impenetrable to me.</p> <p>Can anyone help me either generalize the named_scope example above for my specific case, or point me to a more straightforward strategy?</p> <p>Thanks very much,</p> <p>Dean</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload