Active Record queries ordered by model association: Rails 3 & SQLite
I using Rails 3 and SQLite and I am trying to make an active record query and order the results at the same time using information from another model. I have a resources model(which belongs to user) and a shared_items model to handle users sharing resources with each other. I would like to create a feed of all the resources that a user has created and which have been shared with them. The resource model with a working query:
class Resource < ActiveRecord::Base
has_many :shared_items, :dependent => :destroy
default_scope :order => 'resources.shared_items.created_at DESC'
scope :from_users_sharing_with, lambda { |user| shared_with(user) }
private
def self.shared_with(user)
resource_ids = %(SELECT resource_id FROM shared_items WHERE shared_with_id = :user_id)
where("id IN (#{resource_ids}) OR user_id = :user_id",
{ :user_id => user })
end
This query creates a nice 'feed' array of all the resources that have been shared with or created by the user but they are ordered by the resource create date rather than creation date of the corresponding shared_item which is开发者_Go百科 what I am looking to do. How can I write the ordering at the database level? I thought I could do the ordering in Ruby (like Ian suggests here) but as I am wanting fetch records 25 at a time in pagination, I don't think I can take that option. Any thoughts appreciated.
class Resource < ActiveRecord::Base
has_many :shared_items, :dependent => :destroy
scope :from_users_sharing_with, lambda { |user|
includes(:shared_item).
where("shared_items.shared_with_id = ? OR resources.user_id = ?", user.id, user.id).
order("shared_items.created_at DESC")
# might need to add `select("DISTINCT resources.*")` at the end
}
end
精彩评论