来自一个控制器的多个 rails 5 个嵌套路由

Multiple rails 5 nested routes from one controller

我有 categories/subcategories/products 的嵌套路由,并且相应地设置了我的控制器和视图文件,但我现在有一些没有子类别的产品。如果可能的话,我怎样才能让一些产品属于一个类别,而其他产品属于一个子类别?我看过许多其他关于此的帖子,但 none 似乎正是我想要做的事情。

当前嵌套路由

resources :categories do
  resources :subcategories do
    resources :products
  end
end

额外需要的嵌套路由

resources :categories do
  resources :products
end

我当前的产品控制器创建方法

def create
    @category = Category.friendly.find(params[:category_id])
    @subcategory = Subcategory.friendly.find(params[:subcategory_id])
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to category_subcategory_product_path(@category, @subcategory, @product), notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: category_subcategory_product_path(@category, @subcategory, @product) }
      else
        ...
      end
    end
  end

型号

class Category < ApplicationRecord
  has_many :subcategories
  has_many :products, through: :subcategories
end

class Subcategory < ApplicationRecord
  has_many :products
  belongs_to :category
end

class Product < ApplicationRecord
  belongs_to :subcategory
end

我在这里要做的是删除 Subcategory 模型,让 Categories 属于它们自己。这将允许您创建类别的嵌套层次结构(如果您愿意,这将允许您获得更细化的粒度)。

class Category
  has_many :categories
  belongs_to :category
  has_many :products
end

class Product
  belongs_to :category
end

任何 "top level" 个类别的 category_idnil,任何子类别 belong_to 个现有类别。

top_level = Category.create(slug: "top_level", category_id: nil)
subcategory = Category.create(slug: "subcategory_1", category_id: top_level.id)
Product.create(category: top_level)
Product.create(category: subcategory)

在你的路线中,你可以做这样的事情:

get "/:category/products", to: "products#index"
get "/:category/:subcategory/products", to: "products#index"