我在显示可通过我的应用程序访问的文件时遇到问题。当用户登录时,我想显示他们的所有文件。当前用户下载的文件应该最后显示。文件表有大约 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
我正在使用的技术
- rails 4.2.1
- ruby 2.2.2
- PostgreSQL
最佳答案
老实说,我认为没有必要过度思考这个问题。就数据库负载而言,五百条记录不算什么,因此只需执行两个查询:
您的 Controller 代码
# 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)
然后在您的 View 中依次使用@user_files 和@other_files。有点像
您的 View 代码
<%= render partial: 'files', collection: @other_files %>
<%= render partial: 'files', collection: @user_files %>
UPD
使用 Where Exists gem(披露:我最近发布了它)你可以简化你的 Controller 代码。
取而代之的是:
@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)
关于ruby-on-rails - Rails : Order by associate, 首先未下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810003/