简体   繁体   中英

Rails DateTime - NoMethodError (undefined method `[]' for nil:NilClass)

This is my model:

class User < ActiveRecord::Base
has_many :appointments
has_many :doctors, :through => :appointments
end

class Doctor < ActiveRecord::Base
has_many :appointments
has_many :users, :through => :appointments
end

class Appointment < ActiveRecord::Base
belongs_to :doctor
belongs_to :user
end

Code to call controller action:

$.ajax({
  type: "POST",
  url: "/create",
  data: {
    appointment_date: date,
    doctor_id: "1",
    user_id: "1"
  }

// Etc. });

Action:

def create
    @appointment = Appointment.new(:appointment_date => params[:data][:appointment_date], 
        :hairdresser_id => params[:data][:doctor_id], :user_id => params[:data][:user_id])
    if @appointment.save
        flash[:success] = "Welcome!"
        redirect_to @user
    else
        alert("failure!")
    end
end

And I got this error:

NoMethodError (undefined method `[]' for nil:NilClass)

I'm using FullCalendar plugin and it gets a date in this format:

Fri Sep 13 2013 12:00:50 GMT-0400 (EDT)

I'm saving that date to database in a datetime field.

Any ideas?

When you make and ajax call, you can access the variables like

params[:appointment_date]
params[:doctor_id]
params[:user_id]

and not

params[:data][:appointment_date]
params[:data][:doctor_id]
params[:data][:user_id]

Since there was nothing called params[:data] it gave you a nil class error.

If it is the create action for appointments controller, then it would be

$.ajax({
  type: "POST",
  url: "/appointments",
  data: {
    appointment_date: date,
    doctor_id: "1",
    user_id: "1"
  }

In the create action

def create
    @appointment = Appointment.new({:appointment_date => params['appointment_date'], 
        :hairdresser_id => params['doctor_id'], :user_id => params['user_id]'})
    if @appointment.save
        #YOUR CODE
    else
        #YOUR CODE
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM