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
我沒能找到一個簡單的方法完成我想要的,但也許我忽略了一些東西。