开发者

Rails 3: How do I route a controllers index and show actions to root while sending new/edit/destroy to /admin?

First 开发者_StackOverflow中文版off, I'm using rails 3.0.8 with friendly_id 3.2.1.1.

I'd like to be able to view the posts at website.com/:title, so drop the "/posts".

But I'd also like to have an /admin view. From there, a user should be able to create/edit/destroy posts. I already have a admin.html.erb view with links to various actions.

Right now my routes file look like:

MyApp::Application.routes.draw do
  root :to => 'posts#index'
  resources :posts
  match "/:id" => "posts#show"
  match "/admin" => "posts#admin"
end

This works for website.com/:title, but for website.com/admin I get an error:

Couldn't find Post with ID=admin

.... which makes sense. But I'm not sure how to solve this problem.


The rules are run through top to bottom. So put your admin rule on top of the resource definition.


If you put /admin first then it will work (as noted by cellcortex). You can also use :constraints if you can neatly separate your :id from 'admin'; for example, if your :id values are numeric, then something like this should work:

match '/:id'   => 'posts#show', :constraints => { :id => /\d+/ }
match '/admin' => 'posts#admin'

In a simple case like yours, putting things in the right order will work fine. However, if your routing is more complicated, then the :constraints approach might work better and avoid a some confusion and chaos.


Use this

resource :posts, :path => '/'

with this all of your article will be directly under root

So in Posts Class you may add this:

def to_param
  "#{id}-#{title.parameterize}"
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜