在我的rails应用程序中,时间表包含多个条目,一个条目属于时间表。
class Timesheet < ActiveRecord::Base
has_many :entries, order: 'position', dependent: :destroy
end
class Entry < ActiveRecord::Base
belongs_to :timesheet
end
我正在关注Railscast 147的可排序列表(更新版本)。在开发日志中,我注意到我的params hash正确更新了排序顺序,但是在重新加载时它并没有正确保存位置。此外,创建操作正在处理请求,而不是我的自定义排序操作。这是我的控制器。
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
entries.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'
我搜索了有关未定义方法的错误,但我很困惑为什么在这种情况下会调用create动作呢?我在页面上有一个new_entry表单,它通过Ajax创建一个新条目。也许这会干扰那种?任何帮助,将不胜感激!
答案 0 :(得分:0)
没有'stringify_keys'方法的原因是因为你将数组传递给create动作而不是sort动作。
你在erb.html文件中对data-update-url
有什么看法?
应该是sort_entries_path
。