2011-04-14 125 views
0

我正在嘗試設置共享項目。我將如何使用postgresql在rails中執行此操作?共享項目rails數據庫架構

現在用戶has_many項目。我希望用戶能夠與其他用戶共享項目,但仍擁有這些項目。因此用戶has_many項目和項目has_many用戶。我不能做has_and_belongs_to_many,因爲我希望項目的所有者具有不同於共享用戶的權限。我將如何建立關係?項目是否有一個shared_id,以某種方式指向用戶?

編輯:這是什麼工作

#user.rb 
has_many :items 
has_many :sharrings 
has_many :shared_items, :foreign_key => "item_id", :through => :sharrings, :source => :item 

#user.rb 
belongs_to :user 
has_many :sharrings 
has_many :shared_users, :foreign_key => "user_id", :through => :sharrings, :source => :user 

#sharring.rb 
belongs_to :shareduser 
belongs_to :item 


# create sharring 
@item.sharrings.build :user_id => other_user.id 

# get items shared with this user 
@shared_items = current_user.shared_items 

回答

0

你可以建立兩個獨立的用戶關係 - 一個所有權(的has_many)和一個共享(的has_many:通過)。例如:

#user.rb 
Class User < ActiveRecord::Base 
    has_many :items 
    has_many :shared_items, :foreign_key => "shared_user_id", :through => :item_shares 
end 

#item.rb 
Class Item < ActiveRecord::Base 
    belongs_to :user 
    has_many :shared_users, :foreign_key => "shared_item_id", :through => :item_shares 
end 

#item_share.rb 
Class ItemShare < ActiveRecord::Base 
    belongs_to :shared_user, :class_name => "User" 
    belongs_to :shared_item, :class_name => "Item" 
end 

當你想要分享的項目,剛剛創建的user_id新ItemShare記錄和ITEM_ID設置爲相應的用戶和項目。

你也可以在用戶類中創建一個方法來獲得兩個擁有和共享的項目:

def all_items 
    items + shared_items 
end 
+0

感謝。我會努力實現它。我還在自我參照協會上找到了一個有幫助的欄目。 – Dan 2011-04-14 04:33:36