简体   繁体   中英

model include, must belong to 2 other models

This is really bugging me - cannot seem to get the associations set up correct with includes and so fort. Here are the models in question:

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

I need to output in following structure:

Category.name
 Location.name
  Subcategory.name
  Subcategory.name
  Subcategory.name
       (subcategory from another sub category)

Controller:

 class SubcategoriesController < ApplicationController
    def index
      @categories = Category.all(:include => [:locations => :subcategories], :group
      =>"subcategories.name")
    end

View:

 <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>

what I want is:

 Fruit
  France
    apple
      granny smith
    fig
  India
    pineapple
    banana
 Meat
   India 
     cow
     chicken
     -------------
What I am currently getting:
Fruit
  India
    cow 
    chicken
    banana
    pineapple

Meaning I am getting the subcategories based solely on the location and not on location and category..

My problem arises, when i reach the subcategories level, where subcategories should depend on both category and location - They only ever seem to belong to only 1 of the other models, but in my case they must belong to both. I can't seem to get this right. I have tried numerous ways to do this and not sure im even going about it correctly.

Hope someone can point me in the right direction.

Thanks in advance Christian

If I understand your problem correctly, you have something like

#Category
Fruit
 Apple
 Banana
Vegetable
 Lettuce

#Location
France
 Apple
 Lettuce
India
 Banana

Now, you want something like

#Hierachical output
Fruit
 France
  Apple
 Vegetable
  Lettuce
India
 Fruit
  Banana

In that case, wouldn't this work => location.subcategories.where(category_id: category.id).each ?

Edit :

Perhaps, this could work (in addition to above change):

<%= category.locations.all(include: sub_categories).each do |location|%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM