开发者

sharing items rails database schema

开发者 https://www.devze.com 2023-02-24 06:56 出处:网络
I\'m trying to setup sharing items.How would I do this in rails using postgresql? Right now users has_many items.I want users to be able to share items with other users but still own those items.So u

I'm trying to setup sharing items. How would I do this in rails using postgresql?

Right now users has_many items. I want users to be able to share items with other users but still own those items. So users has_many items and items has_many users. I can't do has_and_belongs_to_many because I want the owner of the item to have different permissions than the shared users. How would I setup the relationship? Should items have a shared_id which somehow points to users?

EDIT: Here's what worked

#user.rb
has_many :items
has_many :sharrings
has_many :shared_items, :foreign_key => "item_id", :thro开发者_如何转开发ugh => :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


You could set up two separate user relationships - one for ownership (has_many) and one for sharing (has_many :through). For example:

#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

When you want to share an item, just create a new ItemShare record with user_id and item_id set to the respective user and item.

You could also create a method within the User class to get both owned and shared items:

def all_items
  items + shared_items
end
0

精彩评论

暂无评论...
验证码 换一张
取 消