rails 中的 4 个模型是否可能存在 has_many 关系? [英] Is a has_many through relationship possible with 4 models in rails?
问题描述
例如,一个列表和一个子列表可以通过名为 list_items 的模型拥有多个项目.
For example a list and a sublist can have many items through a model called 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 模型中填充以下字段
So an item without a sublist (like item 2 and item 4) would have the following fields populated in the List_Item Model
List_id = 1
Sublist_id = nil
Item_id = 1
具有子列表的项目(如项目 5、项目 1 和项目 3)将在 List_Item 模型中填充以下字段
An item with a sublist (like item 5 and item 1 and item 3) would have the following fields populated in the List_Item Model
List_id = 1
Sublist_id = 1
Item_id = 1
我想这样做的原因是我可以通过拖动到子列表来进行拖放操作,它将填充 sublist_id,然后从子列表中拖出 sublist_id 将为零.
The reason i would like to do it this way is so i can do drag and drop by dragging to the sublist it will populate the sublist_id and by dragging out of the sublist the sublist_id will then be nil.
这是可能的还是有更好的方法来做到这一点?
Would this be possible or is there a better way to do this this?
推荐答案
回答您的问题:是的,这是可能的:
To answer your question: Yes, that's possible:
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
关系,如下所示:
If th association on A is named differently than the association on B, you need to supply the source
parameter to the through
-relation, like this:
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
我不确定,这是否能回答您的问题.我希望如此,但我对你的例子有点困惑,所以如果没有,请发表评论:)
I'm not sure, if this answers your question. I hope so, but I'm a little confused about your example, so if not, please do comment :)
这篇关于rails 中的 4 个模型是否可能存在 has_many 关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!