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

前端 未结 8 1195
北恋
北恋 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 03:16

    The M.G.Palmer's approach works well, however table name is involved. There is a better way to do it:

    has_many :users, :through => :assignments, :order => [ :last_name, :first_name ]
    
    0 讨论(0)
  • 2020-12-15 03:16

    This works for me (Rails 4.2)

    Applying an ordering on the through map is not preserved, aka this is not enough to have the genres ordered:

    has_many    :disk_genre_maps,
                -> {order('disk_genre_map.sort_order')},
                :inverse_of => :disk,
                :dependent  => :destroy,
                :autosave   => true
    
    
    has_many    :genres,    # not sorted like disk_genre_maps
                :through    => :disk_genre_maps,
                :source     => :genre,
                :autosave   => true
    

    So I overwrite this per instance:

    def genres  # redefine genres per instance so that the ordering is preserved
        self.disk_genre_maps.map{|dgm|dgm.genre}
    end
    

    To make that work for assignments, this should be something like this (untested)

    def genres= some_genres
        self.disk_genre_maps = some_genres.map.with_index do |genre, index|
            DiskGenreMap.new(disk:self, genre:genre, sort_order:index)
        end
    end
    
    0 讨论(0)
提交回复
热议问题