开发者

Can't get Rails to show JSON Response for action

I have a problem obtaining Json response, I have an action in my controller

def on_card
    @cart = current_cart
    @on_card = @cart.products_count 

    respond_to do |format|
      format.json { render :json=> @on_card.to_json }
    end
end

in my ap开发者_如何学JAVAplication.js I try to get the response form this action var count;

$.getJSON("carts/on_card", function(data){
    count = data;
}); 

when I run it firebug shows me an error:

404 not found

rails can't find carts/on_card action

routes for carts controller:

resources :carts 

  match "carts/add/:id" => "carts#add", :as => "add"

  match "carts/add_menu/:id" => "carts#add_menu", :as => "add_menu"

match "carts/on_card" => "carts#on_card"

log:

Started GET "/carts/on_card" for 127.0.0.1 at 2011-05-24 20:31:58 +0300

AbstractController::ActionNotFound (The action 'show' could not be found for CartsController):

CartsController:
    class CartsController < ApplicationController
  def add
    if current_cart == nil
      @cart = Cart.new    
    else 
      @cart = current_cart
    end

    @cart.products << Product.find(params[:id])

    if @cart.save
      session[:cart_id] = @cart.id
      redirect_to root_path   
    else
      redirect_to root_path
    end
  end

  def add_menu
    if current_cart == nil
      @cart = Cart.new
    else 
      @cart = current_cart
    end

    @cart.menus << Menu.find(params[:id])

    if @cart.save
      session[:cart_id] = @cart.id
      redirect_to root_path   
    else
      redirect_to root_path
    end
  end  

  def index    
    if current_cart !=nil
      @cart = current_cart
    else
      @cart = Cart.new
    end
    respond_to do |format|
      format.html
    end
  end  

  def destroy
    @cart = current_cart
    @product = @cart.products.find(params[:id])
    @product.destroy

    respond_to do |format|
          format.js
    end
  end   

  def on_card
    @cart = current_cart
    @on_card = @cart.products_count 

    respond_to do |format|
      format.json { render :json=> @on_card.to_json }
    end
  end
    end


Move resources :carts to below match "carts/on_card" => "carts#on_card"

You could alternatively add the action as a collection route to your resources :carts

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜