Rails order by in associated model

后端 未结 5 1427
醉酒成梦
醉酒成梦 2020-12-14 06:01

I have two models in a has_many relationship such that Log has_many Items. Rails then nicely sets up things like: some_log.items which returns all of the associ

相关标签:
5条回答
  • 2020-12-14 06:36

    Either of these should work:

    Item.all(:conditions => {:log_id => some_log.id}, :order => "some_col DESC")
    some_log.items.all(:order => "some_col DESC")
    
    0 讨论(0)
  • 2020-12-14 06:36

    set default_scope in your model class

    class Item < ActiveRecord::Base
      default_scope :order => "some_col DESC"
    end
    

    This will work

    0 讨论(0)
  • 2020-12-14 06:50

    order by direct relationship has_many :model

    is answered here by Aaron

    order by joined relationship has_many :modelable, through: :model

    class Tournament
      has_many :games # this is a join table
      has_many :teams, through: :games
    
      # order by :name, assuming team has this column
      def teams
        super.order(:name)
      end
    end
    
    Tournament.first.teams # are returned ordered by name
    
    0 讨论(0)
  • 2020-12-14 06:52

    There are multiple ways to do this:

    If you want all calls to that association to be ordered that way, you can specify the ordering when you create the association, as follows:

    class Log < ActiveRecord::Base
      has_many :items, :order => "some_col DESC"
    end
    

    You could also do this with a named_scope, which would allow that ordering to be easily specified any time Item is accessed:

    class Item < ActiveRecord::Base
      named_scope :ordered, :order => "some_col DESC"
    end
    
    class Log < ActiveRecord::Base
      has_many :items
    end
    
    log.items # uses the default ordering
    log.items.ordered # uses the "some_col DESC" ordering
    

    If you always want the items to be ordered in the same way by default, you can use the (new in Rails 2.3) default_scope method, as follows:

    class Item < ActiveRecord::Base
      default_scope :order => "some_col DESC"
    end
    
    0 讨论(0)
  • 2020-12-14 06:52

    rails 4.2.20 syntax requires calling with a block:

    class Item < ActiveRecord::Base
      default_scope { order('some_col DESC') }
    end
    

    This can also be written with an alternate syntax:

    default_scope { order(some_col: :desc) }
    
    0 讨论(0)
提交回复
热议问题