提问人:userHG 提问时间:11/15/2023 最后编辑:userHG 更新时间:11/16/2023 访问量:60
Rails 中的 FullCalendar 实现
FullCalendar implementation in Rails
问:
我正在 RoR 项目中实现 FullCalendar,当我尝试更新一行时出现此错误:
PATCH http://127.0.0.1:3000/events 404 (Not Found)
这是当我单击事件时更新行的 Ajax 调用:
$.ajax({
type: 'PATCH', // Use PATCH or PUT depending on your Rails routes
url: '/events/' + eventId, // Adjust the URL to your Rails route
data: {
event: {
title: 'updatedTitle',
start_date: 'updatedStartDate',
end_date: 'updatedEndDate',
description: 'updatedDescription'
}
},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
success: function(response) {
if (response.status === 'success') {
// Update the event data in FullCalendar
arg.event.setProp('title', updatedTitle);
arg.event.setStart(updatedStartDate);
arg.event.setEnd(updatedEndDate);
arg.event.setExtendedProp('description', updatedDescription);
// Close the modal
$('#eventModal').modal('hide');
// Display a success message (you can use Swal or other methods)
Swal.fire({
text: 'Event updated successfully',
icon: 'success',
buttonsStyling: false,
confirmButtonText: 'Ok, got it!',
customClass: {
confirmButton: 'btn btn-primary',
}
});
} else {
// Handle the case where the update failed
Swal.fire({
text: 'Event update failed: ' + response.message,
icon: 'error',
buttonsStyling: false,
confirmButtonText: 'Ok, got it!',
customClass: {
confirmButton: 'btn btn-primary',
}
});
}
},
error: function(error) {
console.log('AJAX request to Rails failed.');
console.log(error)
},
});
我console.logged my eventId,并且它已正确实现(其值为76)。我不明白为什么 Ajax 调用使用的 url 是 url: '/events/'
这是我的routes.rb文件:
Rails.application.routes.draw do
resources :telephones
get 'home/index'
resources :tickets
resources :imprimantes
resources :voitures
resources :telephones
resources :events
resources :events do
collection do
post 'import_ics'
get 'export_ics'
end
end
# Define a route for updating events using PATCH
patch '/events/:id', to: 'events#update', as: 'update_event'
resources :google_calendar, only: [:index, :create, :update, :destroy]
root 'home#index'
# Defines the root path route ("/")
# root "posts#index"
end
而更新功能:
def update
@event = Event.find(params[:id])
if @event.update(event_params)
redirect_to events_path
else
render 'edit'
end
def event_params
params.require(:event).permit(:title, :start_date, :end_date, :description)
end
end
我错过了什么?
编辑:Rails控制台日志
Started PATCH "/events/68" for 127.0.0.1 at 2023-11-14 23:55:04 +0100
Processing by EventsController#update as */*
Parameters: {"event"=>{"title"=>"updatedTitle", "start_date"=>"updatedStartDate", "end_date"=>"updatedEndDate", "description"=>"updatedDescription"}, "id"=>"68"}
Event Load (0.5ms) SELECT `events`.* FROM `events` WHERE `events`.`id` = 68 LIMIT 1
↳ app/controllers/events_controller.rb:42:in `update'
TRANSACTION (15.7ms) BEGIN
↳ app/controllers/events_controller.rb:43:in `update'
Event Update (11.3ms) UPDATE `events` SET `events`.`title` = 'updatedTitle', `events`.`start_date` = NULL, `events`.`end_date` = NULL, `events`.`description` = 'updatedDescription', `events`.`updated_at` = '2023-11-14 22:55:04.903524' WHERE `events`.`id` = 68
↳ app/controllers/events_controller.rb:43:in `update'
TRANSACTION (8.0ms) COMMIT
↳ app/controllers/events_controller.rb:43:in `update'
Redirected to http://127.0.0.1:3000/events
Completed 302 Found in 61ms (ActiveRecord: 35.5ms | Allocations: 4141)
Started PATCH "/events" for 127.0.0.1 at 2023-11-14 23:55:04 +0100
ActionController::RoutingError (No route matches [PATCH] "/events"):
答:
2赞
rebelyer
11/15/2023
#1
根据 Rails 日志,看起来您的 JS 触发了一个有效的请求并更新了一条记录。问题是,在成功更新后的控制器中,您可以重定向到events_path
if @event.update(event_params)
redirect_to events_path
else
render 'edit'
end
你能尝试添加一段逻辑来区分 mime 类型的请求吗?
像这样:
def update
@event = Event.find(params[:id])
respond_to do |format|
if @event.update(event_params)
format.html { redirect_to events_path }
format.json { render json: { status: :success } }
else
format.html { render 'edit' }
format.json { render json: { status: :unprocessable_entity } }
end
end
end
链接到源 Mime 响应
此外,您应该在 ajax 调用中添加一个 Accept 标头。您的 ajax 调用应如下所示:
$.ajax({
type: 'PATCH',
url: '/events/1',
headers: {
Accept: "application/json"
},
data: {
event: {
title: 'new_title'
}
},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
success: function(response) {
console.log(response)
// Handle your response
},
error: function(response) {
console.error(response)
// Handle your error
}
})
评论
1赞
userHG
11/15/2023
我尝试了此代码,并遇到了同样的错误
1赞
rebelyer
11/16/2023
我明白了,尝试在ajax调用中添加一个标题'Accept: “application/json”'。您还应该将控制器中的格式从 js 更改为 json。
1赞
userHG
11/16/2023
完美,它有效!谢谢
评论
bin/rails routes | grep events
config/routes.rb