新手问题 關於控制器和路由的問題

1272729223 · September 10, 2012 · Last by 1272729223 replied at September 11, 2012 · 1963 hits

我弄了一個 admin 的後台管理界面,我的controllersviews結構是這樣的:

|-controllers/
|----posts_controller.rb  #此處我寫了`index`, `show`兩個方法.
|----admin/
|----|----posts_controller.rb  #此處我寫了`new`, `edit`, `create`, `update`,`destroy`五個方法.

|-views/
|----posts/
|----|----index.html.erb
|----|----show.html.erb
|----admin/
|----|----posts/
|----|----|----new.html.erb
|----|----|----edit.html.erb
|----|----|----_form.html.erb

然後我的 routes.rb:

#前台的路由
resources :posts, :only => [:index, :show]

#管理員的路由
namespace :admin do
  resources :posts, :except => [:index, :show]
end

admin/posts_controller.rb

def create
  @post = Post.new(params[:post])
  if @post.save
    redirect_to post_path(@post), :notice => "Successfully Posted!"
  else
    render :action => "new"
  end
end

結果是我提交表單之後,返回的路由是http://localhost:3000/posts,並且說no route matches [post] posts/這樣的錯誤提示。

我嘗試去掉routes裡面的onlyexcept限制之後,可以提交,但是需要兩個 posts_controller 都要寫完對應的方法,這樣以來,不是有好幾個多餘的地址出現了?應該的情況是用戶只能看到indexshow, 管理員後台有其他的動作。

是管理页面的表单?确认下 form_for 对应的 action 是不是对的,可以写成 form_for([:admin, @post])

#1 楼 @rociiu 謝謝,已解決,現在乾淨多了,呵呵!

You need to Sign in before reply, if you don't have an account, please Sign up first.