2011-08-09 52 views
2

我正在創建一個用於在用戶之間上傳和共享文件的應用程序。 我有用戶和文件模型,並創建了第三個File_Sharing_Relationships模型,其中包含sharer_id,file_id和shared_with_id列。我希望能夠創建以下方法:Rails 3:我應該使用什麼關聯來創建模型關係

 @upload.file_sharing_relationships - lists users that the file is shared with 
    @user.files_shared_with - lists files that are shared with the user. 
    @user.files_shared - lists files that the user is sharing with others 
    @user.share_file_with - creates a sharing relationship 

是否有任何防護欄協會,如「多態」,我可以使用,使這些關係?

任何建議表示讚賞。謝謝。

回答

1

您只需要閱讀Rails指南並應用所學內容即可。

基本上你需要存儲有關信息:

  • 用戶誰創造了一個「共享」
  • 用戶或用戶組或任何一個分享的動作
  • 資源正在被共享
  • 的目標

所以:

class SharedItem < ActiveRecord::Base 
     belongs_to :sharable, :polymorphic => true #this is user, please think of better name than "sharable"... 
     belongs_to :resource, :polymorphic => true #can be your file 
     belongs_to :user 
end 

你需要SharedItem有:

user_id: integer, sharable_id: integer, sharable_type: string, resource_id: integer, resource_type: string 

然後你就可以得到 「辦法」 通過編寫命名範圍等確定:

named_scope :for_user, lambda {|user| {:conditions => {:user_id => user.id} }} 

或通過指定適當的關聯:

class File < ActiveRecord::Base 
    has_many :shared_items, :as => :resource, :dependent => :destroy 
end 
0

我想你應該建立的關係是這樣的:

class User 
    has_many :files 
    has_many :user_sharings 
    has_many :sharings, :through => :user_sharings 
end 

class File 
    belongs_to :user 
end 

class Sharing 
    has_many :user_sharings 
    has_many :users, :through => :user_sharings 
end 

class UserSharing 
    belongs_to :user 
    belongs_to :sharing 
end 

..這是關係非常基本的模型(這只是我的觀點:))。用戶可以有多個sharings,也屬於sharings。您可以在創建用戶和共享時將文件ID設置爲UserSharing表。然後,您可以使用適當的模型創建上面列出的方法,作爲scopes。我希望我能幫你一點。