1

在我的 Rails 应用程序中,一个 Timesheet has_many Entries 和一个 Entry belongs_to a Timesheet。

class Timesheet < ActiveRecord::Base
  has_many :entries, order: 'position', dependent: :destroy
end


class Entry < ActiveRecord::Base
  belongs_to :timesheet
end

我正在关注 Railscast 147 的可排序列表(更新版本)。在开发日志中,我注意到我的参数哈希正确地更新了排序顺序,但是在重新加载时它没有正确保存位置。此外,请求正在由创建操作而不是我的自定义排序操作​​处理。这是我的控制器。

class EntriesController < ApplicationController
  before_filter :signed_in_user
  before_filter :find_timesheet

  def index
    @entries = @timesheet.entries.order("position")
    @entry = @timesheet.entries.build
  end

  def create
    @entry = @timesheet.entries.build(params[:entry])
    @entry.position = @timesheet.entries.count + 1
    if @entry.save
      #flash[:notice] = "Entry created"
      #redirect_to timesheet_entries_path
      respond_to do |format|
        format.html { redirect_to timesheet_entries_path }
        format.js
      end
    else
      flash[:alert] = "Entry could not be added"
      render 'new'
    end
  end

  def destroy
    @entry = @timesheet.entries.find(params[:id])
    @entry.destroy
    respond_to do |format|
      format.html { redirect_to timesheet_entries_path, flash[:notice] = "Entry destroyed" }
      format.js
    end
  end

  def sort
    params[:entry].each_with_index do |id, index|
      @timesheet.entries.update_all({position: index+1}, {id: id})
    end
    render nothing: true
  end

  private

    def find_timesheet
      @timesheet = Timesheet.find(params[:timesheet_id])
    end  
end

和我的 routes.rb 文件。

Sledsheet::Application.routes.draw do

  resources :timesheets do
    resources :entries, only: [:index, :create, :destroy] do
      collection { post :sort }
    end
  end
end

entry.js.coffee

jQuery -> 
    $("#entries tbody").sortable(
        helper: fixHelper
        update: ->
            $.post($(this).data('update-url'), $(this).sortable('serialize'))
    ).disableSelection()

开发日志的输出

Started POST "/timesheets/8/entries" for 127.0.0.1 at 2012-06-04 20:14:18 -0400
Processing by EntriesController#create as */*
  Parameters: {"entry"=>["60", "59", "61"], "timesheet_id"=>"8"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'qDs53hgOWfRMbNN9JKau3w' LIMIT 1
  Timesheet Load (0.1ms)  SELECT "timesheets".* FROM "timesheets" WHERE "timesheets"."id" = ? ORDER BY date DESC LIMIT 1  [["id", "8"]]
Completed 500 Internal Server Error in 2ms

NoMethodError (undefined method `stringify_keys' for "60":String):
  app/controllers/entries_controller.rb:11:in `create'

我用谷歌搜索了关于未定义方法的错误,但我很困惑为什么在这种情况下无论如何都会调用创建操作?我在页面上有一个 new_entry 表单,它通过 Ajax 创建一个新条目。也许这会干扰排序?任何帮助,将不胜感激!

4

1 回答 1

0

没有 'stringify_keys' 方法的原因是因为您将数组传递给 create 操作而不是 sort 操作。data-update-url您的 erb.html 文件中有什么用途?应该是sort_entries_path

于 2012-06-05T03:26:45.150 回答