共享项目rails数据库架构

时间:2011-04-14 02:39:50

标签: ruby-on-rails activerecord schema

我正在尝试设置共享项目。我如何使用postgresql在rails中执行此操作?

现在用户has_many项目。我希望用户能够与其他用户共享项目,但仍然拥有这些项目。因此,用户has_many项目和项目has_many用户。我不能做has_and_belongs_to_many因为我希望项目的所有者拥有与共享用户不同的权限。我该如何设置关系?项目是否应该以某种方式指向用户的shared_id?

编辑:这是有用的

#user.rb
has_many :items
has_many :sharrings
has_many :shared_items, :foreign_key => "item_id", :through => :sharrings, :source => :item

#user.rb
belongs_to :user
has_many :sharrings
has_many :shared_users, :foreign_key => "user_id", :through => :sharrings, :source => :user

#sharring.rb
belongs_to :shareduser
belongs_to :item


# create sharring
@item.sharrings.build :user_id => other_user.id

# get items shared with this user
@shared_items = current_user.shared_items

1 个答案:

答案 0 :(得分:0)

您可以设置两个单独的用户关系 - 一个用于所有权(has_many),另一个用于共享(has_many:through)。例如:

#user.rb
Class User < ActiveRecord::Base
  has_many :items
  has_many :shared_items, :foreign_key => "shared_user_id", :through => :item_shares
end

#item.rb
Class Item < ActiveRecord::Base
  belongs_to :user
  has_many :shared_users, :foreign_key => "shared_item_id", :through => :item_shares
end

#item_share.rb
Class ItemShare < ActiveRecord::Base
  belongs_to :shared_user, :class_name => "User"
  belongs_to :shared_item, :class_name => "Item"
end

如果您想共享某个项目,只需创建一个新的ItemShare记录,并将user_id和item_id设置为相应的用户和项目。

您还可以在User类中创建一个方法来获取拥有和共享项:

def all_items
  items + shared_items
end