无法让Rails显示JSON响应以执行操作

时间:2011-05-24 16:51:28

标签: json ruby-on-rails-3

我在获取Json响应时遇到问题,我在控制器中有一个动作

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

在我的application.js中我尝试从此操作中获取响应 var count;

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

当我运行它时,firebug向我显示错误:

  

404未找到

     

rails找不到carts / on_card动作

购物车控制器的

路线:

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"

登录

  

在2011-05-24 20:31:58开始获取127.0.0.1的“/ carts / on_card”   0300

     

AbstractController :: ActionNotFound(动作'show'不可能   找到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

1 个答案:

答案 0 :(得分:2)

resources :carts移至match "carts/on_card" => "carts#on_card"

以下

您也可以将操作添加为resources :carts

的收集路线