Rails PATCH方法不起作用

时间:2015-01-29 18:37:55

标签: ruby-on-rails ajax

我正在使用AJAX调用来修补rails数据库。更新控制器接收调用并在数据库中查找元素id,但实际上并未使用新属性更新它。然后它会向AJAX发送成功消息,而不记录任何错误。有什么想法吗?

的Ajax:

eventResizeStop: function(event){
    $.ajax({
        type: "PATCH",
        url: "/appointments/"+event.id,
        data: { appointment: { end_time: event.end.format()} },
        success: function(data){
        },
        error: function(xhr){
            var errors = $.parseJSON(xhr.responseText).errors;
        }
    });
}

Rails控制器:

def update
  @appointment = Appointment.find(params[:id])
  if @appointment.update_attributes(appt_params)
    render nothing: true
    Rails.logger.info(@appointment.errors.full_messages)
  else
    render json: {errors: @appointment.errors.full_messages }, status: 422
  end
end

输出:

Started PATCH "/appointments/2" for 199.94.1.209 at 2015-01-29 18:28:53 +0000
Processing by AppointmentsController#update as */*
Parameters: {"appointment"=>{"end_time"=>"2015-01-30T15:00:00+00:00"}, "id"=>"2"}
Appointment Load (0.2ms)  SELECT  "appointments".* FROM "appointments" WHERE "appointments"."id" = ? LIMIT 1  [["id", 2]]
(0.1ms)  begin transaction
(0.1ms)  commit transaction
Rendered text template (0.0ms)

更新

的routes.rb

 Rails.application.routes.draw do
  get 'houses/new'
  get 'houses/edit'
  get 'sessions/new'
  root 'static_pages#home'
  get 'about'               =>  'static_pages#about'
  get 'contact'             =>  'static_pages#contact'
  get 'signup'              =>  'users#new'
  get    'login'            =>  'sessions#new'
  post   'login'            =>  'sessions#create'
  delete 'logout'           =>  'sessions#destroy'
  get 'newhouse'            =>  'houses#new'
  resources :users
  resources :houses
  resources :appointments,    only: [:index, :create, :update, :destroy]

2 个答案:

答案 0 :(得分:1)

原来我是个白痴。我误读了fullcalendar文档,事实证明eventResizeStop回调并没有包含新的时间,所以AJAX发送了与它已有的数据相同的数据,因此缺少对数据库的更新。

答案 1 :(得分:0)

试试这个:

def update
  @appointment = Appointment.find(params[:id])
  @appointment.end_time = params[:appointment][:end_time]
  if @appointment.save
    render nothing: true
    Rails.logger.info(@appointment.errors.full_messages)
  else
    render json: {errors: @appointment.errors.full_messages }, status: 422
  end
end