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

时间:2015-12-17 22:44:03

标签: javascript ruby-on-rails activerecord

我正在尝试从fullcalendar到rails执行AJAX POST请求,但我没有遇到方法错误,我不知道为什么因为参数似乎没问题。如果我遗漏了事件:来自ajax req所以只发送数据的参数:{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 req:

$.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

1 个答案:

答案 0 :(得分:1)

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

@event = Event.new(event_params)