开发者

Rails 3 Routing: I have "/products?cat=1", I want "/art"

开发者 https://www.devze.com 2023-03-19 06:06 出处:网络
I\'m fairly new to Rails and find myself confused by the routing config. In my project I have 2 models: Product and Category. Product belongs_to Category, Category has_many Product.

I'm fairly new to Rails and find myself confused by the routing config.

In my project I have 2 models: Product and Category. Product belongs_to Category, Category has_many Product.

The Products controller has an index action which takes an optional cat param. When present, the cat param filters the list of products to ones within that category. Pretty basic stuff.

What I want is for mysite.com/art to have the same result as mysite.com/products?cat=1, where "art" is the slug for category 1. I have several other resourceful routes defined, including one for products:

resources :products do
  collection do
    get 开发者_运维问答'search_by_color'
  end
end

I also want to point /products/some-product-slug at products#show

I'm using Rails 3. How can I make this routing set-up happen?


Unless your categories are static and the slugs never change, what you're asking for probably is not advisable. That's because there's no way to statically tell the difference between /art and, say, /about, or /contact, etc. It's also not very RESTful and is therefore frowned upon somewhat by Rails.

That said, if you want to do it anyway, you should write a request constraint. This is any object that responds to matches? and accepts a single argument (the request to match). If it returns true, the route will match and it will be routed in the way you specify. For example, you might write something like:

match '/:category_slug' => 'products#index',
  :constraints => CategorySlugConstraint.new

class CategorySlugConstraint
  def matches?(request)
    Category.find_by_slug ...
  end
end
0

精彩评论

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