【问题标题】:Is there a way to have an association has_many through with join table not obligatory in Rails?有没有办法通过在 Rails 中不需要连接表来建立关联 has_many?
【发布时间】:2020-05-02 11:21:37
【问题描述】:

我想知道如何建立模型的关联以在 Ruby on Rails 中完成任务。我有 3 张桌子。用户、传播和组。组可以有多个用户,用户只能属于一个组。用户组可以拥有自己的点差,但特定用户也可以拥有自己的点差(不属于某个组)。在这种情况下,如何在不创建组的情况下为用户创建点差?

目前我有这些关系:

用户:

has_many :spreads, through :group

组:

has_many :users
has many :spreads

传播:

belong_to :group

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 associations has-many-through model-associations


    【解决方案1】:

    您可以使用Polymorphic Association。所以你的关联会是这样的:

    用户:

    has_many :spreads, as: :parent
    

    组:

    has_many :users
    has many :spreads, as: :parent
    

    传播:

    belong_to :parent, polymorphic: true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-17
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多