2016-04-24 24 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个查询