rails拥有资源控制器和表单以防错误

时间:2013-09-22 14:44:10

标签: ruby-on-rails activeresource

我有数据库表store

型号名称 models / store / store.rb

class Store::Store < ActiveRecord::Base
...
end

controller controllers / store / maintenance_controller.rb

class Store::MaintenanceController < ApplicationController

  def index
    @stores = Store.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @stores }
    end
  end

  def new
    @store = Store.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @store }
    end
  end

的routes.rb

  namespace :store do
    root :to => "store#index"
    resources :store, :path => 'maintenance', controller: 'maintenance', :as => 'maintenance'
  end

rake routes | grep store

      store_root        /store(.:format)                                           store/store#index
  store_maintenance_index GET    /store/maintenance(.:format)                               store/maintenance#index
                        POST   /store/maintenance(.:format)                               store/maintenance#create
    new_store_maintenance GET    /store/maintenance/new(.:format)                           store/maintenance#new
   edit_store_maintenance GET    /store/maintenance/:id/edit(.:format)                      store/maintenance#edit
        store_maintenance GET    /store/maintenance/:id(.:format)                           store/maintenance#show
                        PUT    /store/maintenance/:id(.:format)                           store/maintenance#update
                        DELETE /store/maintenance/:id(.:format)                           store/maintenance#destroy

如果我输入localhost:3000 / store 它的工作,但如果我输入localhost:3000 / store / new im getting error undefined method 'stores_path' for 在线 <%= form_for(@store) do |f| %>

这里有什么问题?谢谢(我已经有商店控制器,这就是为什么我要为商店表重命名控制器,如果我想使用脚手架)

2 个答案:

答案 0 :(得分:0)

您可以尝试将models/store/store.rb移至models/store.rb,然后将该行更改为:

class Store < ActiveRecord::Base
...
end

答案 1 :(得分:0)

您的表单会查找POSTstores_path,但是store_maintenance_index_path您的路线会用于创建操作。所以没有stores_path

您的设置不正确..

stores您没有任何路由资源,仅适用于maintenances ..

所以真正的问题是,你在尝试什么CRUD?是maintenances还是stores

如果您想CRUD stores,请修改您的路线:

namespace :store do
  resources :stores
end

如果你真的想编辑维护的路径名,可以这样:

namespace :store do
  resources :stores, path: 'maintenances', controller: 'stores', as: 'stores'
end

你不想在stores控制器中使用CRUD maintenances,这是不正确的......