これについては他の回答を見てみましたが、私のリダイレクトが機能していない理由がわかりません。Rails redirect_to not working?
私はDevise with Rails 3.1を使用しており、ショッピングサイトを作っています。訪問者は、サインインしていない限りカートに物を追加することはできません。これは私が問題を抱えていることです。サインインしていない場合は、商品インデックスページにリダイレクトします。ここで私が持っているものです。
今のようclass ItemsController < ApplicationController
def add_to_cart
@item = Item.find(params[:id])
if current_user
@item.update_attributes(:cart_id => @current_cart.id)
redirect_to :back
else
redirect_to categories_path, notice: 'You must sign in to add an item to your cart.'
end
end
.
.
.
end
、私はカートに追加するためのリンクをクリックしたときに、この方法は、(私はRailsは、サーバログに@itemをロードし、定義を参照することができます)実行されます、そして、それが到達しました'else'ステートメントはリダイレクトされません。
私は既に索引、新規など(すべてのRESTfulアクション)の足場を生成しました。また、私はadd_to_cartメソッドに到達していると確信しています。なぜなら、いくつかのputステートメントでデバッグを試みたからです。ここで何が起こっていますか?
EDITは:
また、有用であり得る他の奇妙なことは...サーバは二回、このメソッドを実行しようとしているようだ、と二度カテゴリ「取得」しようとします:
Started GET "/items/3/add_to_cart" for 127.0.0.1 at 2012-01-12 16:53:11 -0800 Processing by ItemsController#add_to_cart as JS Parameters: {"id"=>"3"} Category Load (0.3ms) SELECT "categories".* FROM "categories" Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT 1 [["id", "3"]] Redirected to http://localhost:3000/categories Completed 302 Found in 26ms
Started GET "/items/3/add_to_cart" for 127.0.0.1 at 2012-01-12 16:53:11 -0800 Processing by ItemsController#add_to_cart as JS Parameters: {"id"=>"3"} Category Load (0.2ms) SELECT "categories".* FROM "categories" Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT 1 [["id", "3"]] Redirected to http://localhost:3000/categories Completed 302 Found in 25ms
Started GET "/categories" for 127.0.0.1 at 2012-01-12 16:53:12 -0800 Processing by CategoriesController#index as JS Category Load (0.2ms) SELECT "categories".* FROM "categories" CACHE (0.0ms) SELECT "categories".* FROM "categories" Rendered categories/index.html.erb within layouts/application (0.0ms) Completed 200 OK in 35ms (Views: 28.5ms | ActiveRecord: 4.2ms)
Started GET "/categories" for 127.0.0.1 at 2012-01-12 16:53:12 -0800 Processing by CategoriesController#index as JS Category Load (0.2ms) SELECT "categories".* FROM "categories" CACHE (0.0ms) SELECT "categories".* FROM "categories" Rendered categories/index.html.erb within layouts/application (0.0ms) Completed 200 OK in 37ms (Views: 30.6ms | ActiveRecord: 4.2ms)
EDIT 2(DELBAによって要求された)
resources :items do
member do
get 'add_to_cart'
end
end
EDIT 3:答えを必要とするかもしれない人のためのjavascript
respond_to do |format|
format.js { redirect_to items_path, notice: 'You must sign in to add an item to your cart.' }
end
に持っているあなたは、Ajaxのフォームを使用していないのですか? ( 'remote:true') – Damien
@Delbaはい。カートに追加するリンクは次のとおりです:%= link_to 'カートに入れる'、{:コントローラ=>「アイテム」、アクション=>「add_to_cart」、:id => item.id}、 \t:remote => true %> – varatis
あなたは 'add_to_cart'にGETを使うべきではありません。 POSTを使用します。あなたのルートを投稿してください。 – Damien