【问题标题】:Rails create mapping to wrong routeRails 创建到错误路线的映射
【发布时间】:2016-01-20 16:12:51
【问题描述】:

我有一个 Rails 表单来为商店创建配置文件。最初,我因此处理了路由resources :stores,一切都很好。但是,我想在管理范围和“公共”范围之间划分我的商店资源。完成此操作后,表单提交停止工作,向我传递错误“没有路由匹配 [POST]“/admin/stores””。我不清楚为什么会这样,因为我认为我适当地分配了我的资源......

scope "/admin" do
    resources :stores, only: [:index, :edit, :update, :destroy]
end

resources :stores, only: [:new, :create]

这里是控制器动作...

def new
    @store = current_user.stores.new
    @store.build_address
    @storeType = StoreType.all
end

def create
    @store = current_user.stores.new(store_params)

    if @store.save
        flash[:notice] = "New store created"
        redirect_to root_path
    else
        #ERROR STUFF
    end
end

我在 Rails 路由信息中注意到的一件事是,创建的 POST 操作与所有其他 /admin 前缀资源集中到 store_path 中

stores_path 
   GET  /admin/stores(.:format) stores#index
edit_store_path 
   GET  /admin/stores/:id/edit(.:format)    stores#edit
store_path
   PATCH    /admin/stores/:id(.:format) stores#update
   PUT  /admin/stores/:id(.:format) stores#update
   DELETE   /admin/stores/:id(.:format) stores#destroy
   POST /stores(.:format)   stores#create
new_store_path
   GET  /stores/new(.:format)   stores#new

我不确定我是否理解为什么会发生这种情况,任何帮助将不胜感激。为什么当我将 :new 和 :create 操作放在“公共”路由中时,表单会尝试发布到管理员路由?

非常感谢。

【问题讨论】:

  • 表单是否只使用form_for(@store)
  • 我不确定我是否理解;你在问为什么createstore_path 列在其他store_path HTTP 方法下?我的意思是,URL 是正确的,它是 store_path,而且一切似乎都是正确的。
  • 它不是发布到管理员路由,它显示它将发布到的路由。

标签: ruby-on-rails ruby-on-rails-4 routes


【解决方案1】:

POST 被路由到 create 操作,您在 resources 调用中明确说明了要省略 create 操作的操作

把它改成这个,它应该可以工作

scope "/admin" do
    resources :stores, only: [:index, :create, :edit, :update, :destroy]
end

如果您想使用当前命名空间(管理员)之外的路由,您需要将url: store_path 选项传递给表单助手,并指定method: :post 选项。

【讨论】:

    猜你喜欢
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2012-05-30
    • 2010-09-18
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多