多级has_many,通过has_and_belongs_to_many

问题描述 投票:1回答:1

我正在尝试在Rails中建立三层关系,看起来像这样。

+---------+      +---------+
| Brand 1 |      | Brand 2 |
++------+-+      +---+---+-+
 |      `------------|---|-------------.
 |                   |   `-----------. |
+v-----------+    +--v---------+    +v-v---------+
| Category 1 |    | Category 2 |    | Category 3 |
++------+----+    +--+-+-------+    +----------+-+
 |      |            | |                       |
 |      `----------. | `-------------.         `---------.
+v-----------+    +v-v---------+    +v-----------+    +--v---------+
| Template 1 |    | Template 2 |    | Template 3 |    | Template 4 |
+------------+    +------------+    +------------+    +------------+

注意,Template 2Category 1Category 2的成员,并且这些类别中的每个类别均具有不同的品牌。同样,请注意Category 3在两个品牌之间共享。

现在的关系定义如下。

class Brand < ApplicationRecord
  has_many :categories
  has_many :templates, through: :categories
end

class Category < ApplicationRecord
  belongs_to :brand
  has_and_belongs_to_many :templates
end

class Template < ApplicationRecord
  has_and_belongs_to_many :categories
  has_many :brands, through: :categories
end

我无法更新Brand-Template关系,因此没有模板按品牌“过滤”,因为类别是共享的。我目前收到此错误。

ActiveRecord :: HasManyThroughNestedAssociationsAreReadonly位于/ templates / 7无法修改关联“ Template#brands”,因为它涉及多个关联。

如何更改Brand-Template关系来解决此问题?

ruby-on-rails has-many-through
1个回答
0
投票

我已经将Brand-Template更改为has_and_belongs_to_many。现在,我可以像这样在Template上写一个作用域:

© www.soinside.com 2019 - 2024. All rights reserved.