2016-04-24 26 views
0

我遇到了顯示專櫃類別的小問題。我想要在我的索引頁面上顯示類別名稱和圖像,類別名稱充當到類別頁面的鏈接,其中顯示此類別的產品。我有我的看法如下代碼:專櫃類別路由

<% @products.each do |category, products| %> 
    <%= link_to category.name, product_category_path %> 
<% end %> 

但它返回我一個錯誤undefined local variable or method 'product_category_path' for #<#<Class:0xb22076fc>:0xb2205870>

我應該爲類控制器,以及用於產品?因爲現在我只有products_controller.rb用下面的代碼:

class ProductsController < ApplicationController 
    def index 
     @products = Shoppe::Product.root.ordered.includes(:product_categories, :variants) 
     @products = @products.group_by(&:product_category) 
    end 
    def show 
     @product = Shoppe::Product.root.find_by_permalink(params[:permalink]) 
    end 
end 
+0

您能否看到'rake routes'並查看您是否使用了正確的路由幫助器路徑 – illusionist

+0

u應該沒問題,只需傳遞一個類別id'<% = link_to category.name,product_category_path(category.id)%>' – 7urkm3n

回答

0

我不清楚你有什麼想在這裏實現,但錯誤信息是非常明確的。如果您運行rake routes你不會找到一個名爲​​

你需要把

resources :products do 
    resources :categories 
end 

routes.rb文件的路徑,你需要創建一個CategoriesControllershow行動

的原因我我很困惑是

<%= link_to category.name, product_category_path %> 

​​手段你想這樣

/products/:product_id/categories/:id(.:format) 

一個網址,你必須使用product_category_path(product, category)

但它確實適合你的,你想要做什麼說明。什麼你真的想可能只是簡單category_path,在這種情況下,你可以與所有產品訪問分類頁面屬於像這樣

/categories/:id(.:format) 

,併爲您查看,你可以做

<%= link_to category.name, category_path(category) %> 

你還需要與action創建CategoriesController,但不會要求product_id

控制器代碼可能看起來像這樣(假設你設置的關聯正確)

class CategoriesController < ApplicationController 
    def show 
    @category = Category.includes(:products).find(params[:id]) 
    end 
end 
+0

這就是我在'rake routes'內所具有的:'product_category GET /product_categories/:id(.:format)shoppe/product_categories#show' – AlexNikolaev94

+0

@ AlexNikolaev94' shoppe/product_categories#show'告訴導軌尋找'Shoppe :: ProductCategories'控制器並在那裏調用'show'動作。如果我正確理解你的代碼,你有'product_categories'聯合表。有聯合模型的觀點並不常見,在你的情況下聽起來沒有必要。 –

+1

@卓梁Takuto Xing您的解決方案是完善的,但也取決於用例。如果針對類別的「顯示」操作需要是不同的視圖,而該視圖沒有任何產品,但只是關於該類別的信息?如果需要的話,我認爲使用會員路線會使應用程序在將來更容易更改。 –

0

我覺得railsy方法是:

1)創建CategoriesController

2)註冊爲會員的路線

在你的路線:

resources :categories do 
    member do 
    get :products 
    end 
end 

您的幫手將會是products_category_path(@category),網址將是/categories/:id/products

成員路線將自定義動作products添加到您的控制器。

你的索引視圖會有這樣的:

<% @products.each do |product| %> 
    <%= link_to product.category.name, products_category_path(product.category) %> 
<% end %> 

CategoriesController你會:

def products 
    Shoppe::Product.where(category_id: params[:id]) 
end 

注:在您的產品索引操作中包含產品類別以避免N + 1個查詢