2013-12-21 39 views
0

如何在多對多關係中添加所有權?用戶和文件的多對多關係及其在rails中的所有權

例如像這樣的模型。

class User < ActiveRecord::Base 
    has_many :editabilities, dependent: :destroy 
    has_many :files, through: :editabilities 
end 

class File < ActiveRecord::Base 
    has_many :editabilities, dependent: :destroy 
    has_many :users, through: :editabilities 
end 

class Editabilities < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :file 
end 

我想爲用戶和文件添加一對多關係。

起初我認爲最好是將owner布爾列添加到Editabilities,但我不知道如何處理它。

其次,我想如果我做一個新的路口模型Ownerships,那麼我可以像Editabilities一樣處理。但是當我用這樣的代碼嘗試它時,我得到了一個uninitialized constant User::Ownership

class User < ActiveRecord::Base 
    has_many :editabilities, dependent: :destroy 
    has_many :ownerships, dependent: :destroy 
    has_many :files, through: :editabilities 
    has_many :owned_files, through: :ownerships, source: :file 
end 

class File < ActiveRecord::Base 
    has_many :editabilities, dependent: :destroy 
    has_many :ownerships, dependent: :destroy 
    has_many :users, through: :editabilities 
    has_one :owner, through: :ownerships, source: :user 
end 

class Editabilities < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :file 
end 

class Ownerships < ActiveReord::Base 
    belongs_to :user 
    belongs_to :file 
end 

我該如何實現這樣的功能?

回答

0

我在這裏看到的唯一問題是類EditabilitiesOwnerships。通過Rails公約模型,類名應該是單數,而不是複數。

class Editability < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :file 
end 

class Ownership < ActiveReord::Base 
    belongs_to :user 
    belongs_to :file 
end 

一種方法來快速檢查你的類名是通過檢查classify函數的結果:

> "editibilities".classify 
=> "Editibility" 

> "ownerships".classify 
=> "Ownership" 

協會的其餘全部看起來是正確的。

0

你的班級應該被命名爲Ownership而不是Ownerships。 ActiveRecord類名通常是單數,表名是複數。

更簡單的解決方案似乎將belongs_to關聯添加到File模型。因爲1個文件只能擁有1個所有者。

class File < ActiveRecord::Base 
    ... 
    belongs_to :owner, class_name: 'User' 
end 

您需要將owner_id列添加到文件表中。