Rails验证会在更新时跳过

时间:2014-08-14 10:10:34

标签: ruby-on-rails validation ruby-on-rails-4

我有两个按钮保存并提交。如果提交已触发,则应运行验证,否则应跳过验证。在我的控制器创建和更新方法中,我定义了这样的条件以确保。

创建行动

@applicant = Applicant.new(applicant_params)
build_images
if !params[:submit_button].blank?

  if !@applicant.save
    render 'new'
  else
    redirect_to users_applicants_path, notice: 'Competition application successfully created.'
  end
else
  @applicant.save(:validate => false)
  redirect_to users_applicants_path, notice: 'Competition application successfully created.'
end

更新行动

@applicant = Applicant.find(params[:id])
build_images
@applicant.assign_attributes(applicant_params)
if !params[:submit_button].blank?

  if !@applicant.save
    render 'edit'
  else
    redirect_to users_applicants_path, notice: 'Competition application successfully updated.'
  end
else
  @applicant.save(:validate => false)
  redirect_to users_applicants_path, notice: 'Competition application successfully updated.'
end

当我想第一次提交表单时,验证工作正常,但是当我保存然后尝试提交验证时,仅适用于申请人和伴奏模型,但不适用于照片和视频。申请人有一个伴奏和有很多照片和视频。问题出在更新的某个地方,但我不是为什么这么做。

2 个答案:

答案 0 :(得分:0)

update方法中尝试此操作: -

@model_name.attributes = params[:model_name]
@model_name.save false

答案 1 :(得分:0)

我设法通过添加

来解决问题

validates_associated :children来建模。

现在一切正常。