例如,一个列表和一个子列表可以通过名为list_items的模型有很多项目。是否可以通过rails中的4个模型建立has_many关系?
下面是模型
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将为零。
这可能吗?还是有更好的方法来做到这一点?
你在'Item'模型中的'associations'是错误的FYI。 – Pavan
所有的关联似乎都很好。 –
我只是改变了它有一个额外的has_many:列表,通过:: list_items在我的项目模型 – EliteViper7777