2

我的路线.rb:

Temp::Application.routes.draw do
  resources :categories, path: '', only: [:index] do
    resources :entries, path: '', only: [:index, :show]
  end
end

这导致以下路线:

  $ rake routes
    category_entries GET /:category_id(.:format)     entries#index
      category_entry GET /:category_id/:id(.:format) entries#show
          categories GET /                           categories#index

问题:我可以以某种方式指定以下参数::category_id,:id?

更详细...我需要这个,因为我不想在我的路径中使用 ID,而是使用名称,例如:http://localhost:3000/cat1/ent11. 我的条目控制器是:

class EntriesController < ApplicationController
  def index
    @entries = Category.where(name: params[:category_id]).first.entries
  end

  def show
    entries = Category.where(name: params[:category_id]).first.entries
    @entry = entries.select { |e|
      e.name == params[:id]
    } .first
  end
end

如果我可以写一些类似的东西,而不是params[:category_id],这段代码会更容易理解: ,。 我怎样才能做到这一点?params[:id]params[:category_name]params[:entry_name]

更新:我想保持我的路线足智多谋......

4

1 回答 1

1

在您的 routes.rb 中,您可以添加该行

match ':controller/:action/:category_name/:entry_name'

让某个控制器接收您想要的参数。请参阅http://guides.rubyonrails.org/routing.html#non-resourceful-routes

于 2012-06-08T06:33:28.920 回答