【问题标题】:jQuery AJAX POST to Rails Controller. Error when doing each_with_index (TypeError can't convert Symbol into Integer)jQuery AJAX POST 到 Rails 控制器。执行 each_with_index 时出错(TypeError 无法将 Symbol 转换为 Integer)
【发布时间】:2012-11-05 03:22:12
【问题描述】:

我正在尝试将 jQuery-UI 可排序连接列表的位置保存到 Rails 后端。尝试将参数保存到数据库时,我遇到了 Rails 控制器操作问题。我得到的错误是TypeError (can't convert Symbol into Integer):

我发送的 Ajax POST 请求中的参数看起来像这样,看起来不错:

Activity:[{"id":"65","column":"48"},{"id":"65","column":"48"},{"id":"67","column":"48"}]

我的 Rails 控制器操作是这样的(我正在尝试使用 'id' 的 id 更新 Activity 并使用 'position' 和 day_id 更新属性 position 和 'column':

  def sort
    JSON.parse(params[:Activity]).each_with_index do |x, index|
      id = x["id"]
      position = index+1
      column = x["column"]
      Activity.update_all(position = position, day_id = column, id = id)
    end
    render nothing: true
  end

我在终端中收到此错误:

    Started POST "/trips/sort" for 10.0.2.2 at 2012-11-04 23:52:30 +0000
Processing by TripsController#sort as */*
  Parameters: {"Activity"=>"[{\"id\":\"66\",\"column\":\"49\"},{\"id\":\"66\",\"column\":\"49\"},{\"id\":\"67\",\"column\":\"49\"}]"}
Completed 500 Internal Server Error in 1ms

TypeError (can't convert Symbol into Integer):

如果有帮助,这是我的 jQuery AJAX 调用:

    jQuery ->
  $('[id*="day"]').sortable(
    connectWith: ".day"
    placeholder: "ui-state-highlight"
    update: (event, ui) ->
      neworder = new Array()
      $(this).children().each ->
        column = $(this).parent().attr("id").match(/\d+/)[0]
        id = $(this).attr("id").match(/\d+/)[0]
        neworder.push(
          id: id
          column: column
        )
      alert neworder
      $.ajax
        url: "sort"
        type: "POST"
        data: { Activity: JSON.stringify(neworder) }
    ).disableSelection()

过去几个小时我一直在研究这个问题,但还是想不通。非常感谢您的时间和帮助。

【问题讨论】:

    标签: jquery ruby-on-rails ajax ruby-on-rails-3 jquery-ui


    【解决方案1】:

    您想单独更新每个活动,如下所示:

    JSON.parse(params[:Activity]).each_with_index do |x, index|
      id = x["id"]
      position = index+1
      column = x["column"]
      activity = Activity.find(id)
      activity.update_attributes(:position=>position, :column=>column)
    end
    

    (假设您的 JSON 解析工作正常,我没有检查过)

    Activity.update_all 将更新所有具有相同属性的活动(例如,将所有活动设置为第 5 列和位置 1),这不是您想要在此处完成的。

    【讨论】:

    • 太棒了!我很困惑,因为我认为我得到的错误是由于 JSON 解析造成的。事实证明,我在使用 update_all 时遇到了错误。我曾认为 update_all 与 update_attributes 相同,唯一的区别是 update_all 使用单个数据库调用而不是调用每个属性来更新所有属性。谢谢! @aguynamedloren
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多