2016-05-19 31 views
0

在我的應用程序中,用戶可以在此刻創建產品User has_many :productsProduct belongs_to :user。現在我希望產品創建者product.user能夠邀請其他用戶加入該產品,但我想讓創作者成爲唯一可以編輯該產品的人。與不同角色(擁有者,非擁有者)的rails連接表問題

我想到的其中一個設置是這樣的,但我想這是行不通的,因爲我不知道如何區分創建的和「加入邀請」的產品,當撥打user.products

User 
has_many :products, through: :product_membership 
has_many :product_memberships 
has_many :products # this is the line I currently have but think it wouldn't 
        # work with the new setup 

Product 
has_many :users, through: :product_membership 
has_many :product_memberships 
belongs_to :user # I also have this currently but I'd keep the user_id on the product 
       # table so I could call product.user and get the creator. 

ProductUsers 
belongs_to :user 
belongs_to :product 

Invitation 
belongs_to :product 
belongs_to :sender, class: "User" 
belongs_to :recipient, class: "User" 

要解決這個問題,我能想到的2個解決方案:

  1. 擺脫User has_many :products線,我目前擁有的和簡單地增加一個實例方法的user型號:

    def owned_products 
        Product.where("user_id = ?", self.id) 
    end 
    

    我的這個問題,我猜它不符合約定。

  2. 擺脫我目前擁有的User has_many :products系列,並向名爲is_owner?的'ProductUsers'添加一個布爾列。我沒有嘗試過,所以我不知道這是如何工作的。

什麼是解決此問題的最佳解決方案?如果沒有這些,請讓我知道你的建議。我不想在以後遇到一些問題,因爲我的數據庫架構被搞砸了。

回答

0

您可以將admincreator屬性添加到ProductUsers表中,默認情況下將其設置爲false,並將其設置爲true以供創建者使用。

編輯:這就是你所說的is_owner? 這似乎是一個相當不錯的解決方案,並且很容易讓你找到創建者。

product.product_memberships.where(is_owner?: true)

應該給你的創造者