Rails Active Record: find in conjunction with :order and :group

前端 未结 2 1826
耶瑟儿~
耶瑟儿~ 2021-01-01 08:03

I have a structure something like this:

class User
  has_many :dongles
  has_many :licences, :through => :dongles
end

class Dongle
  has_many :licences
          


        
2条回答
  •  没有蜡笔的小新
    2021-01-01 08:13

    Have you tried with a default scope? First, you can try to add the order in the has_many as I've shown in the User.

    class User
      has_many :dongles
      has_many :licences, :through => :dongles, :order => 'created_at DESC'
    end
    

    However, I am not sure if that actually works with a has-many-through association, maybe, if that doesn't work you can try to add it to the association in Dongle instead.

    class Dongle
      has_many :licences, :order => 'created_at DESC'
      belongs_to :user
    end
    

    The second option would be to try with a default scope as I've shown in the License.

    class Licence
      default_scope :order => 'created_at DESC'
      belongs_to :dongle
    end
    

    after that it should be enough to just get it with user.licenses.find(:first)

提交回复
热议问题