1
目前我正在开发一个应用程序,涵盖了一些非常基本的文档管理。 在此期间,弹出一个问题。Rails has_many通过默认值ActiveRecord
下面是这种情况:
我对用户文档(用户可以下载许多文件和文档可以通过许多用户下载)经典的许多一对多的关系。
这个应用程序里面有“公共文件”,每个人都应该可以访问。
这里显而易见的解决方案是将“公共文档”添加到每个新用户的映射表中。但这真是太天真了,我不想写一个将这些元素插入映射表的例程,这也会浪费数据库存储。
问题
是否有Rails的方式来增加这些公共文件(这是通过标志标)在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
我没能找到一个简单的方法完成我想要的,但也许我忽略了一些东西。