如果我尝试从学生模型更新属性,则由于验证而失败。
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/activerecord-5.0.1/lib/active_record/validations.rb:78:in`
任何人都知道如何解决这个问题?
谢谢!
答案 0 :(得分:0)
如果对象验证失败,update
方法将调用验证并不保存。当您尝试更新特定属性时,建议您改为使用update_attribute
或update_column
。
只需更改
@student.update(student_params)
到
@student.update_attribute(beschikbaar: params[:beschikbaar])
或强>
@student.update_column(beschikbaar: params[:beschikbaar])