jeudi 1 février 2018

(undefined method `year' for nil:NilClass) when saving date

I have a ruby on rails app. I added date_field to the view for add/Edit dates. the problem is that I have problem for saving and updating new dates but it brings the date from variable to the form(Edit) and after editting a date and creatine a new date. it doesn't come back to the home page or have problem with saving. as I saw in the console params, my date variable(start) changed when the user select new date but it does not load the first page afterward and I got this error:

    F, [2018-02-01T16:03:44.784113 #723] FATAL -- : 
NoMethodError (undefined method `year' for nil:NilClass):
  app/controllers/weeks_controller.rb:27:in `create'

here is my form page where it shows date to edit:

 .form-group
    = f.label :course
    = @course.name
  .form-group.form-inline
    = f.label :start
    = f.date_field :start, as: :date, value: f.object.try(:strftime,"%m/%d/%Y"), class: 'form-control'
    //= f.date_select :start, {}, { :class => "form-control" }
  .actions
    = f.submit 'Save', :class => "btn btn-primary"

an the error says about controller. but I do not have any 'year' method in controller:

 def create
     @week = Week.new(week_params.merge(course_id: @course.id))
     respond_to do |format|
     if @week.save
         format.html { redirect_to '/weeks', notice: 'was successfully created.' }
         format.json { render action: 'show', status: :created, location: @week }
       else
         format.html { render action: 'new' }
         format.json { render json: @week.errors, status: :unprocessable_entity }
       end
     end
  end



 def update
     respond_to do |format|
       if @week.update(week_params)
        format.html { redirect_to '/weeks', notice: 'starting week was successfully updated.' }
        format.json { head :no_content }
       else
         format.html { render action: 'edit' }
         format.json { render json: @week.errors, status: :unprocessable_entity }
       end
     end
   end

weeks_params defined as follows:

def week_params
      params.require(:week).permit(:start, :course_id)
    end

I have at first problem of showing date with date_select but now with date_field it shows that but I do not know where this error refers to. I would be thankful if any one would help me.

Aucun commentaire:

Enregistrer un commentaire