1

我在显示可通过我的应用程序访问的文件时遇到问题。当用户登录时,我想显示他们的所有文件。当前用户下载的文件应该最后显示。文件表有大约 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

我正在使用的技术

  • 导轨 4.2.1
  • 红宝石 2.2.2
  • PostgreSQL
4

1 回答 1

0

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

您的控制器代码

# 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)
于 2015-08-04T15:25:25.370 回答