【问题标题】:Rails 3: What associations should I use to create model relationshipsRails 3:我应该使用什么关联来创建模型关系
【发布时间】:2011-08-09 14:15:12
【问题描述】:

我正在创建一个用于在用户之间上传和共享文件的应用。 我有用户和文件模型,并创建了第三个 File_Sharing_Relationships 模型,其中包含一个 sharer_id、file_id 和 shared_with_id 列。我希望能够创建以下方法:

     @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

是否有任何 Rails 关联,例如我可以用来建立这些关系的“多态”?

任何建议表示赞赏。谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 models


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      我认为您应该像这样创建关系:

      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 在适当的模型中。希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-20
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        相关资源
        最近更新 更多