How do I order a has_many through association in Ruby on Rails?

前端 未结 8 1194
北恋
北恋 2020-12-15 02:45

Given the following AR models, I would like to sort users alphabetically by last name when given a handle to a task:

#user
has_many :assignments
has_many :ta         


        
相关标签:
8条回答
  • 2020-12-15 02:50

    I am using Rails (5.0.0.1) and could make the sort with this syntax in my model Group that has many users through group_users:

    # Associations.
    has_many :group_users
    has_many :users, -> { order(:name) }, through: :group_users
    

    Adjust the code to your need that will work.

    0 讨论(0)
  • 2020-12-15 02:53

    Rails 3.x version:

    has_many :users, :through => :assignments, :order => 'users.last_name, users.first_name'
    

    UPDATE: This only works in Rails 3.x (maybe before that too). For 4+, see other answers.

    0 讨论(0)
  • 2020-12-15 02:54

    You could also create a new 'sort_order' column on the assignment table, and add a default scope like

    default_scope { order('sort_order desc')}
    

    to your assignments model.

    0 讨论(0)
  • 2020-12-15 03:04

    Since condition arguments are deprecated in Rails 4, one should use scope blocks:

    has_many :users, -> { order 'users.last_name, users.first_name' }, :through => :assignments
    
    0 讨论(0)
  • 2020-12-15 03:09

    Would this work for you?

    # User.rb
    
    class User < ActiveRecord::Base
     default_scope :order => 'last_name ASC'
     ...
    end
    

    You can define other named scopes for when sorting needs to be different.

    http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

    0 讨论(0)
  • 2020-12-15 03:10

    has_many :users, -> { order(:last_name, :first_name) }, :through => :assignments, source: 'user'

    0 讨论(0)
提交回复
热议问题