【问题标题】:sharing items rails database schema共享项目 rails 数据库模式
【发布时间】:2015-12-03 00:23:37
【问题描述】:

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

现在用户有_many 个项目。我希望用户能够与其他用户共享项目,但仍然拥有这些项目。所以 users has_many items 和 items has_many users。我不能做 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

【问题讨论】:

    标签: ruby-on-rails activerecord schema


    【解决方案1】:

    您可以设置两种不同的用户关系 - 一种用于所有权 (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
    

    【讨论】:

    • 谢谢。我会尝试实现它。我还发现了一个关于自我参照协会的 railscast 插曲,这很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多