【问题标题】:rails join table issue with different roles (owner, non-owner)rails join table issue with different roles (owner, non-owner)
【发布时间】:2016-09-16 16:06:57
【问题描述】:

在我的应用中,用户现在可以创建产品User has_many :productsProduct belongs_to :user。现在我希望产品创建者product.user 能够邀请其他用户加入产品,但我想让创建者成为唯一可以编辑产品的人。

我想到的设置之一是这个,但我想它不会起作用,因为我不知道如何在致电 @987654324 时区分创建的产品和“通过邀请加入”的产品@。

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”添加一个布尔列。我以前没有尝试过,所以我不确定这会如何。

解决此问题的最佳解决方案是什么?如果这些都不是,请告诉我您的建议。我不想在以后遇到一些问题,因为我的数据库架构搞砸了。

【问题讨论】:

    标签: ruby-on-rails associations schema


    【解决方案1】:

    您可以在ProductUsers 表中添加admincreator 属性,并将其默认设置为false,并为创建者设置为true。

    编辑:这就是你所说的is_owner? 这对我来说似乎是一个相当不错的解决方案,并且可以让您轻松找到创建者。

    product.product_memberships.where(is_owner?: true)

    应该给你创造者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-02
      • 2017-02-12
      • 1970-01-01
      • 2015-11-03
      • 2022-10-06
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      相关资源
      最近更新 更多