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

1272729223 · 2012年09月10日 · 最后由 1272729223 回复于 2012年09月11日 · 1961 次阅读

我弄了一個 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 謝謝,已解決,現在乾淨多了,呵呵!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号