共享项目Rails数据库模式

| 我正在尝试设置共享项。我如何使用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
    
已邀请:
您可以建立两个单独的用户关系-一个用于所有权(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
    

要回复问题请先登录注册