AJAX POST请求上没有方法错误轨道

no method error rails on AJAX POST request

本文关键字:有方法 错误 轨道 POST 请求 AJAX      更新时间:2023-09-26

我正在尝试从fullcalendar到rails进行AJAX POST请求,但我没有得到方法错误,我不知道为什么,因为参数似乎很好。如果我忽略了ajax请求中的event:,所以只发送数据这样的参数:{title:title,sender_id:senderId..},那么我会得到同样的错误。我错过了什么?

Started POST "/users/1/events" for ::1 at 2015-12-17 14:33:12 -0800
14:33:12 puma.1       | Processing by EventsController#create as */*
14:33:12 puma.1       |   Parameters: {"event"=>{"title"=>"asdfasdfadsf", "start_at"=>"Fri, 18 Dec 2015 00:00:00 GMT", "end_at"=>"Sat, 19 Dec 2015 00:00:00 GMT", "sender_id"=>"1", "recipient_id"=>"2"}, "user_id"=>"1"}
14:33:12 puma.1       |   User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
14:33:12 puma.1       | Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.3ms)
14:33:12 puma.1       | 
14:33:12 puma.1       | NoMethodError - undefined method `save' for nil:NilClass:

ajax请求:

$.ajax({
   type: "POST",
   url: "/users/1/events",
   data: { event: {
         title: title,
         start_at: "" + new Date(start).toUTCString(),
         end_at: "" + new Date(end).toUTCString(),
         sender_id: 1,
         recipient_id: 2
         }}
   });

事件控制器:

def create
  respond_to do |format|
    if @event.save
      format.html { redirect_to @event, :notice => 'Event was successfully created.' }
      format.json { render :json => @event, :status => :created, :location => @event }
    else
      format.html { render :action => "new" }
      format.json { render :json => @event.errors, :status => :unprocessable_entity }
    end
  end
end

private
def event_params
  params[:start_at] = params[:start]
  params[:end_at] = params[:end]
  params[:recipient_id] = params[:recipientId]
  params[:sender_id] = params[:senderId]
  params[:all_day] = params[:allDay]
  params.require(:event).permit(:recipient_id, :sender_id, :title, :body, :start_at, :end_at, :all_day)
end

event.rb

def as_json(options = {})
    { id: self.id,
      recipientId: self.recipient_id,
      senderId: self.sender_id,
      title: self.title,
      body: self.body || "",
      start: start_at,
      :end => end_at,
      allDay: self.all_day,
      recurring: false, 
      url: Rails.application.routes.url_helpers.user_event_path(self.recipient_id, self.id)
    }
  end

您已经定义了event_params方法,但没有在任何地方调用它。在create方法中,在顶部(假设@event的类是Event),添加行

@event = Event.new(event_params)