2011-08-09 8 views
2

ユーザー間でファイルをアップロードおよび共有するためのアプリを作成しています。 私はUser and Filesモデルを持っており、sharer_id、file_id、およびshared_with_idの列を含む3番目のFile_Sharing_Relationshipsモデルを作成しました。私は、次のメソッドを作成することができるようにしたい: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 
    

    が...これは関係の非常に基本的なモデル(これは、ビューの私のポイントです:))です。ユーザーは多くのシャーリングを持つことができ、シャーリングにも属します。ユーザーとその共有を作成するときに、ファイルIDをUserSharingテーブルに設定することができます。上に挙げたメソッドを適切なモデルにscopesとして作成することができます。私はあなたを少し助けてくれることを願っています。

    関連する問題