1
假設我們有一個用戶。在Rails中,如何將這兩個不同的has_manys合併爲一個?
用戶的has_many文件通過賬號是這樣的...
class User < ActiveRecord::Base
belongs_to :account
has_many :documents, :through => :account, :order => "created_at DESC"
end
class Account < ActiveRecord::Base
has_one :owner, :class_name => "User", :dependent => :destroy
has_many :documents, :dependent => :destroy
end
class Document < ActiveRecord::Base
belongs_to :account
end
尼斯和簡單,這是它得到棘手......
用戶也可對文檔進行協作,這通過合作者加入表...
class Collaborator < ActiveRecord::Base
belongs_to :user
belongs_to :documnet
end
class Document < ActiveRecord::Base
has_many :collaborators, :dependent => :destroy
has_many :users, :through => :collaborators
accepts_nested_attributes_for :collaborators, :allow_destroy => true
end
這是我不確定的最終用戶位。我想補充另一個有很多的文件,當你調用user.documents它融合通過他們的帳戶,他們正在合作開發的那些兩個文件...
class User < ActiveRecord::Base
belongs_to :account
has_many :documents, :through => :account, :order => "created_at DESC"
#documents need to do both has manys…
has_many :collaborators, :dependent => :destroy
has_many :documents, :through => :collaborators
end
謝謝,這是一個有點長,但我能想到的一個整潔的解決方案。任何幫助將非常感激。
謝謝!我修改了一下,使其工作,添加我的更改。乾杯。 – Smickie