由于验证,更新失败

时间:2017-08-22 20:05:27

标签: ruby-on-rails postgresql validation attributes sql-update

如果我尝试从学生模型更新属性,则由于验证而失败。

  def update
    @student = Student.find(params[:id])
    if params['student']
      if params['student']['freedays']
        weekday_nbs = params['student']['freedays']&.first&.split(',')
        params['student']['freedays'] = weekday_nbs.inject([]){|sum, last| sum << Student::FREE_DAYS[last.to_i]}
      end
      if params['student']['vehicles']
        params['student']['vehicles'] = params['student']['vehicles']&.split(',')
      end
      if params['student']['driving_licenses']
        params['student']['driving_licenses'] = params['student']['driving_licenses']&.split(',')
      end
    end
    @student.update(student_params)
    redirect_to student_path(@student)
  end

这是我尝试更新属性时遇到的错误(:beschikbaar):

`ActiveRecord::RecordInvalid: Validation failed: First name can't be blank, Last name can't be blank, Age can't be blank, Photo can't be blank, Studie can't be blank, Description can't be blank, Phone number can't be blank from /home/yves/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/ac‌​tiverecord-5.0.1/lib‌​/active_record/valid‌​ations.rb:78:in`

任何人都知道如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果对象验证失败,update方法将调用验证不保存。当您尝试更新特定属性时,建议您改为使用update_attributeupdate_column

只需更改

@student.update(student_params)

@student.update_attribute(beschikbaar: params[:beschikbaar])

@student.update_column(beschikbaar: params[:beschikbaar])