technix
technix

Reputation: 419

Rails 3: What associations should I use to create model relationships

I am creating an app for uploading and sharing files between users. I have User and Files models and have created a third File_Sharing_Relationships model which contains a sharer_id, file_id and shared_with_id columns. I want to be able to create the following methods:

     @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

Are there any rails associations, such as 'polymorphic' that I could be using to make these relationships?

Any suggestions appreciated. Thanks.

Upvotes: 2

Views: 154

Answers (2)

socjopata
socjopata

Reputation: 5095

All you need to do is to read Rails Guides and apply all what you learn.

Basically you need to store info about:

  • user who created a "sharing"
  • user or group or whatever is a target of a sharing action
  • resource that is being shared

So:

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

You need SharedItem to have:

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

Then you can get "methods" you specified by writing named scopes like:

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

or by specifying proper associations:

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

Upvotes: 1

bor1s
bor1s

Reputation: 4113

I think you should create relationships something like this:

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

.. this is very basic model of relations(It is just my point of view :)). User can have many sharings and also belongs to sharings. You can set file id to UserSharing table when you create user and it's share. And then you can create methods, you listed above, as scopes in proper models. I hope I helped you a little.

Upvotes: 0

Related Questions