2015-07-11 75 views
0

例如,一个列表和一个子列表可以通过名为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将为零。

这可能吗?还是有更好的方法来做到这一点?

+0

你在'Item'模型中的'associations'是错误的FYI。 – Pavan

+0

所有的关联似乎都很好。 –

+1

我只是改变了它有一个额外的has_many:列表,通过:: list_items在我的项目模型 – EliteViper7777

回答

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 

如果日上的一个关联要比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 

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

+0

你是一类短:如果有第四个模型,如果有一个类D,这将工作如何? – BKSpurgeon

+0

你可以继续这个链条,只要你愿意。只需将适当的belongs_to添加到后续的新类和has_many,直到类链。 –

+0

我应该写信来修改你的答案,如果我想连接D类和A类,该怎么办? – BKSpurgeon

相关问题