Rails has_many 通过默认值 ActiveRecord

Rails has_many through default values ActiveRecord

目前我正在开发一个应用程序,它涵盖了一些非常基本的文档管理。 这期间,突然出现了一个问题。

场景如下:

我有一个典型的用户和文档的多对多关系(一个用户可以下载很多文档,一个文档可以被很多用户下载)。

此应用程序中有 "public documents" 每个人都应该可以访问的内容。

这里最明显(和天真的)的解决方案是为每个新用户将 "public documents" 添加到映射 table 中。但这真的很天真,我不想编写将这些元素插入到映射中的例程 table,这也会浪费数据库存储空间。

问题

在 Rails 中有没有办法将那些 public 文档(通过标志标记)添加到 ActiveRecord 中的用户可下载文档?

示例:

文档

Id   |   Name   |   IsPublic
------------------------------
1    |   Test   |   false
2    |  Public  |   true

用户

Id   |   Name
--------------------
1    |   sternze

可下载文件:

User_id   |   Doc_id
----------------------
   1      |      1

我现在想要做的是:

@user = User.find(1)
@user.documents  # -->  now contains documents 1 & 2
# I don't want to add rows to the documents inside the controller, because the data is dynamically loaded inside the views.

我的协会如下:

class User < ApplicationRecord
  has_many :downloadable_documents
  has_many :documents, through: :downloadable_documents
end

class DownloadableDocuments < ApplicationRecord
  belongs_to :user
  belongs_to :document
end

class Document < ApplicationRecord
  has_many :downloadable_documents
  has_many :users, through: :downloadable_documents
end

我找不到一种简单的方法来完成我想要的,但也许我忽略了一些东西。

在文档中为 public 个文档创建范围

class Document
  scope :public, -> {public?}
end

创建用户方法'all_documents'

class User

  def all_documents
    documents + Document.public
  end

end

然后在迭代中使用 all_documents 而不是 documents