Ruby on rails Rails 3:我应该使用什么关联来创建模型关系
我正在创建一个应用程序,用于在用户之间上载和共享文件。 我有用户和文件模型,并创建了第三个文件共享关系模型,其中包含共享者id、文件id和共享id列。我希望能够创建以下方法:Ruby on rails Rails 3:我应该使用什么关联来创建模型关系,ruby-on-rails,ruby-on-rails-3,models,Ruby On Rails,Ruby On Rails 3,Models,我正在创建一个应用程序,用于在用户之间上载和共享文件。 我有用户和文件模型,并创建了第三个文件共享关系模型,其中包含共享者id、文件id和共享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.
@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关联,例如“多态性”可以用来建立这些关系
如有任何建议,我们将不胜感激。谢谢。我认为你应该建立这样的关系:
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设置为UserShareing表。然后,您可以在适当的模型中创建上面列出的方法,如
作用域
。我希望我能帮你一点忙。你所需要做的就是阅读Rails指南并应用所学知识
基本上,您需要存储以下信息:
- 创建“共享”的用户
- 用户或组或任何共享操作的目标
- 正在共享的资源
named_scope :for_user, lambda {|user| {:conditions => {:user_id => user.id} }}
或通过指定适当的关联:
class File < ActiveRecord::Base
has_many :shared_items, :as => :resource, :dependent => :destroy
end
类文件named_scope :for_user, lambda {|user| {:conditions => {:user_id => user.id} }}
class File < ActiveRecord::Base
has_many :shared_items, :as => :resource, :dependent => :destroy
end