2013-10-23 38 views
0

我有一個Rails應用程序,用戶可以在其中創建筆記本並與其他用戶共享。用戶可以編輯關於他們自己的筆記本電腦的所有內容,但只有部分筆記本電腦與他們共享。現在我的模型是這樣的:允許部分多對多訪問模型

class User < ActiveRecord::Base 
    has_many :notebooks 

    # other user things... 
end 

class Notebook < ActiveRecord::Base 
    belongs_to :user 

    # other notebook things... 
end 

而在我的控制器,我允許用戶編輯自己的筆記本電腦。現在我需要弄清楚如何讓其他用戶訪問與他們共享的部分筆記本。我想要做類似於:

class Notebook < ActiveRecord::Base 
    belongs_to :user # the admin user for this notebook 
    has_many :users # all users with access 
end 

我不確定如何設置,因爲我是新手Rails。有關如何構造這些數據的任何建議?

回答

0

你簽出has_many_and_belongs_to?或has_many, :through?查看Rails指南here

class Notebook < ActiveRecord::Base 
    has_many :users, through: :user_notebooks 
end 

class User < ActiveRecord::Base 
    has_many :notebooks, through: :user_notebooks 
end 

而且,看你的多個(即,它應該是has_many :users,不has_many :user)。

+0

看起來'has_and_belongs_to_many'可以讓我創建多對多的關係,但是如何以這種方式強制執行筆記本的所有權呢?如果不區分所有者和允許訪問的人,我是不是隻能得到'notebook.users'? – Peter

+0

那麼'Notebook'中的':owner'或':creator'字段怎麼樣,並且存儲創建者的用戶ID? –