【发布时间】: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