开发者

Rails routes question. Always find by name and remove /class_name/ from route

I have a Category model and a Product model.

Category has_many products 

and

Product belongs_to Category
开发者_如何学JAVA

I want my routes to be like this:

/:category_type/:category_name/  opens Product#index
/:category_type/  opens Category#index

/ opens Category#index

Is there a way to achieve that with resources? I tried with path_prefix but I just can't get it done.

Any help?

Thanks,

Nicolás Hock Isaza


Maybe this will help:

ActionController::Routing::Routes.draw do |map|

  map.category '/:category_type/', :controller => 'categories'
  map.category_products '/:category_type/:category_name/', :controller => 'products'
  map.root :controller => 'categories'

end

class CategoriesController < ApplicationController
  def index
    @categories = Category.find(:all) unless params[:category_type]
    @categories = Category.find_all_by_category_type if params[:category_type]
  end
end

class ProductsController < ApplicationController
  def index
    @category = Category.find_by_name(params[:category_name])
    @products = @category.products.find(:all)
  end
end

In this case you'll get categories filtred by type at '/:category_type/' and all categories at root path '/'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜