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

前端 未结 2 1804
耶瑟儿~
耶瑟儿~ 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:09

    From your models, all association info has already been declared. You can actually use each of user to access dongles and licences info by performing a single query with ActiveRecord include options.

    # Say the table name is licences and dongles.
    users = User.find(:all, 
      :include => [:dongles, :licences], 
      :order => "licences.created_at DESC, dongles.created_at DESC")
    

    I assume you want to create a summary of latest licence of each dongle owned by each user. You may cut the loop upon your actual needs.

    users.each do |user| 
      # do something with your user info
      user.dongles.each do |dongle|
        # do something with your dongle info
        licence = dongle.licences.first
        # do something with the licence info
      end
    end
    

    Read more about this at http://snippets.dzone.com/posts/show/2089

    0 讨论(0)
  • 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)

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