Rails: 按关联排序,先不下载

Rails: Order by associate, first not downloaded

我在显示可通过我的应用程序访问的文件时遇到问题。当用户登录时,我想显示他们的所有文件。当前用户下载的文件应该最后显示。文件table有大约500条记录,所以我需要简单快速的方法来实现。

class User
  has_many :downloads
  has_many :downloaded_files, :through => :downloads, source: :file
end

class File 
  attr_accessor :downloaded

  has_many :downloads
  has_many :users, :through => :downloads
end

class Download
  belongs_to :user
  belongs_to :file
end

我使用的技术

老实说,我认为没有必要过度思考这个问题。就数据库负载而言,五百条记录不算什么,因此只需启动两个查询:

您的控制器代码

# Current user files
@user_files = current_user.downloaded_files

# Select all files which don't have Download record for current user
@other_files = File.where("NOT EXISTS (SELECT 1 FROM downloads WHERE file_id = files.id AND user_id = ?)", current_user.id)

然后在你的视图中依次使用@user_files和@other_files即可。像

您的视图代码

<%= render partial: 'files', collection: @other_files %>
<%= render partial: 'files', collection: @user_files %>

UPD

使用Where Exists gem(披露:我最近发布了它)你可以简化你的控制器代码。

而不是这个:

@other_files = File.where("NOT EXISTS (SELECT 1 FROM downloads WHERE file_id = files.id AND user_id = ?)", current_user.id)

你可以这么写:

@other_files = File.where_not_exists(:downloads, user_id: current_user.id)