使用javascript对列表进行排序工作正常,但是当我刷新页面时,排序列表会返回其原始位置而不是保存。看起来POST请求似乎不起作用。
我的控制器
class SlidesController < ApplicationController
before_filter :authenticate_user!
def index
@slides = Slide.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @slides }
end
end
def sort
@slides = slide.all
@slides.each do |slide|
slide.position = params['slide'].index(slide.id.to_s) + 1
slide.save
end
end
def create
@status = Status.find(params[:status_id])
@slide = @status.slides.create(params[:slide])
respond_to do |format|
if @slide.save
format.html { redirect_to (status_path(@status, :anchor => "form")) }
format.json { render json: @status, slide: :created, location: @status }
else
format.html { redirect_to @status, alert: 'Contents of slide must be between 1 - 200 characters long.' }
format.json { render json: @slide.errors, slide: :unprocessable_entity }
end
end
end
def destroy
@status = Status.find(params[:status_id])
@slide = @status.slides.find(params[:id])
@slide.destroy
redirect_to status_path(@status)
end
def edit
@status = Status.find(params[:status_id])
@slide = @status.slides.find(params[:id])
end
def update
@status = Status.find(params[:status_id])
@slide = @status.slides.find(params[:id])
@slide.update_attributes(params[:slide])
redirect_to (status_path(@status, :anchor => "slide_#{(@slide.id)}"))
end
end
对列表javascript进行排序
$(document).ready(function () {
$('#slides').sortable({
axis : 'y',
dropOnEmpty : false,
handle : '.handle',
cursor : 'crosshair',
items : 'li',
opacity : 0.4,
scroll : true,
update : function () {
$.ajax({
type : 'POST',
beforeSend : function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
data : $('#slides').sortable('serialize'),
dataType : 'script',
complete : function (request) {
$('#slides').effect('highlight');
},
url : '/statuses'
})
}
});
});
幻灯片模型
class Slide < ActiveRecord::Base
attr_accessible :content
belongs_to :status
validates :content, presence: true, length: { minimum: 1, maximum: 200 }
acts_as_list
end