Rails 3:只在某个方法中路由错误



我在我的routes.rb中遇到了一个奇怪的行为。以下是我的routes.rb节选:

resources :stores do
  resources :stores_spare_parts do
    collection do
      post :update_attribute_on_the_spot
    end
  end
end

当我现在在stores_spare_parts控制器的索引操作中调用方法url_for时,它返回http://127.0.0.1:3000/stores/1/stores_spare_parts/update_attribute_on_the_spot。但是,当我在创建操作中执行相同操作时,它会停止工作,并出现以下错误:

ActionController::RoutingError
(No route matches  {:action=>"update_attribute_on_the_spot",
:controller=>"stores_spare_parts"}):
app/controllers/stores_spare_parts_controller.rb:19:in `block in create'
app/controllers/stores_spare_parts_controller.rb:19:in `create'

下面是索引和create方法的控制器代码:

def index
  Rails.logger.debug { "---------------------------" }
  Rails.logger.debug { url_for(:action => 'update_attribute_on_the_spot') }
  Rails.logger.debug { "---------------------------" }
  @currentStore = Store.find(params[:store_id])
  @activeStores = Store.scoped_by_deactivated(false)
  @storesSpareParts = StoresSparePart.scoped_by_store_id(@currentStore.id)
end
def create
  Rails.logger.debug { "---------------------------" }
  Rails.logger.debug { url_for(:action => 'update_attribute_on_the_spot') }
  Rails.logger.debug { "---------------------------" }
  return
  @newStoreSparePart = StoresSparePart.new(params[:stores_spare_part])
  if @newStoreSparePart.save
    flash[:notice] = "Successfully updated spare part for store #{@newStoreSparePart.store.title}."
    @currentStore = @newStoreSparePart.store
    @activeStores = Store.scoped_by_deactivated(false)
    @storesSpareParts = StoresSparePart.scoped_by_store_id(@currentStore.id)
    Rails.logger.debug { @currentStore.title }
    Rails.logger.debug { @storesSpareParts.count }
    render 'create.js'
  else
    render 'create.js'
  end
end
下面是传递给create方法的POST请求:
Started POST "/stores_spare_parts" for 127.0.0.1 at 2011-05-02 17:52:00 +0200
Processing by StoresSparePartsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"+NKTAC8ibgUW8vYg5H0XcWB+hAoFdw6on3Uw2XfP9WQ=", 
"stores_spare_part"=>{"spare_part_id"=>"6", "quantity"=>"2", 
"lowMark"=>"", "store_id"=>"1"}, "commit"=>"Create Stores spare part"}

post :update_attribute_on_the_spot更改为put :update_attribute_on_the_spot,因为看起来您正在更新记录(put)而不是创建记录(post)。我敢肯定,有一次我做了像你做的那样的事,RoR对我很生气。

相关内容

  • 没有找到相关文章

最新更新