无法在视图中显示我的类别和子类别 Rails 4

Can't display my category and subcategory in the views Rails 4

我的网站有类别和子类别,这是我的 seeds.rb 中的内容,我在那里创建了一个名为 "Video and animation" 的主类别和 4 个子类别,然后我将子类别分配给主类别类别。

@category = Category.create!(name:  "Video and animation")

["Intro", "Animation & 3D", "Editing and Post Production", "Other"].each do |name|

@subcategory = Subcategory.create!(name: name, category_id: @category.id)

end

它运行良好,在我的 rails 控制台中我看到一切正常,添加产品的 category_id 更改为数字(应该是整数)。

问题:如何在我的视图中显示类别,以便当有人点击它时他会获得该类别的所有产品。 我如何按照相同的原则显示所有子类别。 这是我试图在我的观点中表达的内容

<% Category.all.each do |category| %>
  <%= link_to category.name, gigs_path(category: category.name) %>
<% end %>
<% Subcategory.all.each do |subcategory| %>
  <%= link_to subcategory.name, gigs_path(subcategory: subcategory.name) %>
<% end %>

奇怪的是,当我放入我的产品控制器时 这个

def index
      @category_id = Category.find_by(name: params[:category])
      @gigs = Gig.where(category_id: @category_id).order("created_at DESC")
      @subcategory_id = Subcategory.find_by(name: params[:subcategory])
      @gigs = Gig.where(subcategory_id: @subcategory_id).order("created_at DESC")
  end 

如我所愿,它只显示了所需的子类别,但主要类别仍然是空的。 如果我把它放到我的控制器中

def index
      @category_id = Category.find_by(name: params[:category])
      @subcategory_id = Subcategory.find_by(name: params[:subcategory])
      @gigs = Gig.where(category_id: @category_id).order("created_at DESC")
  end

根据需要,主类别有效,但子类别仍为空。

注意:在这两种情况下,在视图中,在任何人单击任何内容之前,我都会看到显示的正确类别和子类别。

这是我在 3 个模型中的每一个模型

class Category < ActiveRecord::Base
  has_many :subcategories
end

class Subcategory < ActiveRecord::Base
  belongs_to :category
  has_many :products
end

class Product < ActiveRecord::Base
  acts_as_votable
  belongs_to :user
  belongs_to :subcategory
  has_attached_file :image, :styles => { :medium => "300x300>" }
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end

感谢您的宝贵时间。

在控制器动作中

@categories = Category.includes(:subcategories)

添加浏览量

<% @categories.each do |category| %>
     <%= link_to category.name, gigs_path(category: category.name) %>
     <% category.subcategories.each do |subcategory| %>
          <%= link_to subcategory.name, gigs_path(subcategory: subcategory.name) %>
     <% end %>
<% end %>

更改控制器中的索引方法

def index
    if params[:category]
        c_id = Category.find(name: params[:category])
        @gigs = Gig.where(category_id: c_id).order("created_at DESC")
    elsif params[:subcategory]    
        subc_id = Subcategory.find(name: params[:subcategory])
        @gigs = Gig.where(subcategory_id: subc_id).order("created_at DESC")
    end    
end