【问题标题】:Is a has_many through relationship possible with 4 models in rails?是否有可能与 Rails 中的 4 个模型建立 has_many through 关系?
【发布时间】:2015-07-11 15:22:28
【问题描述】:

例如,一个列表和一个子列表可以通过一个名为 list_items 的模型包含许多项。

这是模型

class List < ActiveRecord::Base
    has_many :sublists
    has_many :list_items
    has_many :items, through: :list_items
end

class Sublist < ActiveRecord::Base
    belongs_to :list
    has_many :list_items
    has_many :items, through: :list_items
end

class Item < ActiveRecord::Base
    has_many :list_items
    has_many :lists,through: :list_items
    has_many :sublists, through: :list_items
end

class ListItem < ActiveRecord::Base
  belongs_to :list
  belongs_to :sublist
  belongs_to :item
end

这就是我想要完成的。

项目库页面

Item 1
Item 2
Item 3
Item 4
Item 5 

列表页面

=============================
=List 1                     =
=============================
=Item 2                     =
=Item 4                     =
=Sublist Start              =
=Item 5                     =
=Item 1                     =
=Item 3                     =
=============================

因此,没有子列表的项目(如项目 2 和项目 4)将在 List_Item 模型中填充以下字段

List_id = 1

Sublist_id = nil

Item_id = 1

具有子列表的项目(如项目 5、项目 1 和项目 3)将在 List_Item 模型中填充以下字段

List_id = 1

Sublist_id = 1

Item_id = 1

我想这样做的原因是,我可以通过拖动到子列表来进行拖放,它将填充 sublist_id,并且通过拖出子列表,sublist_id 将为 nil。

这可能吗,或者有更好的方法来做到这一点?

【问题讨论】:

  • 您在Item 模型中的associations 错误仅供参考。
  • 所有关联似乎都很好。
  • 我刚刚改了,在我的项目模型中多了一个 has_many :lists, through: :list_items

标签: ruby-on-rails ruby-on-rails-4 relationships


【解决方案1】:

回答您的问题:是的,这是可能的:

class A
  has_many :bs
  has_many :cs, through: :bs
  has_many :ds, through: :cs
end

class B
  has_many :cs
  belongs_to :a
end

class C
  has_many :ds
  belongs_to :b
end

class D
  belongs_to :c
end

如果 A 上的关联与 B 上的关联命名不同,则需要将 source 参数提供给 through-relation,如下所示:

class A
  has_many :bs
  has_many :cs, through: :bs, source: :ccs
end

class B
  has_many :cs, as: :ccs
  belongs_to :a
end

class C
  belongs_to :b
end

这将允许您:

A.find(1).bs # => collection of B-instances
A.find(1).cs # => collection of C-instances

我不确定这是否能回答您的问题。我希望如此,但我对你的例子有点困惑,所以如果没有,请发表评论:)

【讨论】:

  • 你还差一个类:如果有第四个模型——即如果有一个 D 类,这一切将如何运作?
  • 您可以随心所欲地继续这条链。只需将适当的 belongs_to 添加到后续的新类和 has_many 一直到类链的上游。
  • 要我写信修改你的答案,如果我想连接D类和A类怎么办?
  • 你继续你需要添加has_many :ds到类A的链,然后通过继承树一直链接它。
  • 好的。我在示例中添加了附加类。您应该认真阅读 ActiveRecord 的关系,以更好地了解解决方案。
猜你喜欢
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多