通过AJAX调用更新/销毁Rails模型

时间:2015-12-25 14:05:28

标签: jquery ruby-on-rails ajax post

我正在尝试使用前端的AJAX调用来更新我的Rails模型,但无法正确实现它。

我的路线是:

  authenticated :customer do
    post 'update_card/:id', to: 'customers/cards#update'
    post 'delete_card/:id', to: 'customers/cards#destroy'
  end

这是我的处理请求的控制器:

class Customers::CardsController < ApplicationController
  before_filter :authenticate_customer!

  def update
    if customer_signed_in?
      card_to_update = JSON.parse(params)

      card = current_customer.discount_cards.find(params[:id])

     # do the update... (update_attributes ?)

      render json: card
    end
    render status: :not_found, json: 'error'
  end

  def destroy
    # nothing yet
  end
end

这就是我进行AJAX调用的方式:

    $.ajax({
        type: 'POST',
        url: `/update_card/${this.props.cardId}.json`,
        data: JSON.stringify({
            name: newName,
            description: newDesc,
            shopName: newShopName,
        }),
        success: (msg) => {
            console.log('Data Saved: ' + msg);
        },
    });

我无法弄清楚我错过了什么并不断收到此错误:

  

TypeError - 没有ActionController :: Parameters的隐式转换   到字符串

您能否帮我正确实施更新和销毁方法?

更新

我已经更改了update方法,现在看起来像这样:

  def update
    if customer_signed_in?

      card = current_customer.discount_cards.find(params[:id])

      card.name ||= params[:name]
      card.description ||= params[:description]
      card.shop.name = params[:shopName] if params[:shopName] && card.shop

      card.save!
      current_customer.save!

      render json: { status: 'updated', object: card.to_json }
    else
      render json: { status: 'failed', errors: ['error'] }
    end
  end

现在ajax中没有JSON.stringify调用

但是,数据不会被保存。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

JSON.parse方法允许将字符串作为参数而不是散列。

card_to_update = JSON.parse(params)

paramsActionController::Parameters,是rails env。

中的哈希

为什么需要JSON.stringify?传递给data只是一个对象。

data: {
   name: newName,
   description: newDesc,
   shopName: newShopName
},

然后在Rails中使用它:

# some code here
card_to_update = { name: params[:name],
                   description: params[:description],
                   shopName: params[:shopName] }
# some code here

或其他版本:

data: { toUpdate: {
   name: newName,
   description: newDesc,
   shopName: newShopName
} },

滑轨:

card_to_update = params[:toUpdate]