다른 답변을 찾으려고했지만 리디렉션이 작동하지 않는 이유를 알 수 없습니다.Rails가 redirect_to가 작동하지 않습니까?
그래서 저는 Devise와 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
, 방법은 실행됩니다 (I 서버 로그에 레일로드 및 정의 @item을 볼 수 있습니다), 그리고에 도달 : 여기에 내가 가진 무엇 'else'문은 리디렉션이 발생하지 않습니다.
나는 이미 색인, 신규 등 (모든 RESTful 조치)에 대한 스캐 폴딩을 생성했습니다. 또한 일부 puts 문을 사용하여 디버깅을 시도했기 때문에 add_to_cart 메서드에 도달 할 것이라고 확신합니다. 여기 무슨 일 이니?
편집 :
또한, 사용이 될 수있는 또 다른 이상한 점은 ... 서버가 두 번이 방법을 실행하려고하는 것, 그리고 두 번 범주 '수'를 시도 :
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)
편집 2 (DELBA의 요청에 따라)
resources :items do
member do
get 'add_to_cart'
end
end
편집 3 : 답변을해야 할 수도 있습니다 누군가를 위해 자바 스크립트
respond_to do |format|
format.js { redirect_to items_path, notice: 'You must sign in to add an item to your cart.' }
end
당신이 아약스 양식을 사용하고 있습니까 포함? ('remote : true') – Damien
@ 델바 예. 다음은 장바구니에 추가 할 링크입니다 : % = link_to '장바구니에 담기', {: controller => "items", : action => "add_to_cart", : id => item.id}, \t : remote => true %> – varatis
'add_to_cart'에 GET을 사용하면 안됩니다. POST를 사용하십시오. 당신의 노선을 게시하십시오. – Damien