这真的很困扰我 - 似乎无法正确设置包含等关联。以下是有问题的模型:
class Category < ActiveRecord::Base
has_many :subcategories
has_many :locations, :through => :subcategories
end
class Location < ActiveRecord::Base
has_many :subcategories
has_many :category, :through => :subcategories
end
class Subcategory < ActiveRecord::Base
belongs_to :category
belongs_to :location
end
我需要以以下结构输出:
Category.name
Location.name
Subcategory.name
Subcategory.name
Subcategory.name
(subcategory from another sub category)
控制器:
class SubcategoriesController < ApplicationController
def index
@categories = Category.all(:include => [:locations => :subcategories], :group
=>"subcategories.name")
end
视图:
<div class="categorylist">
<ul>
<%= @categories.each do |category|%>
<h3>
<%=h link_to category.name, category %>
</h3>
<%= category.locations.each do |location|%>
<h6>
<%= link_to location.name, location %>
</h6>
<%= location.subcategories.each do |subcategory|%>
<p>
<%= link_to subcategory.name, subcategory%>
</p>
<% end %>
<% end %>
<% end %>
</ul>
</div>
我想要的是:
Fruit
France
apple
granny smith
fig
India
pineapple
banana
Meat
India
cow
chicken
-------------
What I am currently getting:
Fruit
India
cow
chicken
banana
pineapple
这意味着我仅根据位置而不是位置和类别获得子类别。
当我达到子类别级别时,我的问题出现了,其中子类别应该同时取决于类别和位置 - 它们似乎只属于其他模型中的一个,但就我而言,它们必须同时属于两者。我似乎做不好。我已经尝试了许多方法来做到这一点,但不确定我是否正确。
希望有人能为我指出正确的方向。
提前致谢基督教
如果我正确理解您的问题,您有类似的东西
#Category
Fruit
Apple
Banana
Vegetable
Lettuce
#Location
France
Apple
Lettuce
India
Banana
现在,你想要类似的东西
#Hierachical output
Fruit
France
Apple
Vegetable
Lettuce
India
Fruit
Banana
在这种情况下,这不会起作用吗 => location.subcategories.where(category_id: category.id).each
?
编辑:
也许,这可以工作(除了上述更改):
<%= category.locations.all(include: sub_categories).each do |location|%>