【问题标题】:Rails validation skips on updateRails 验证在更新时跳过
【发布时间】:2014-08-14 10:10:33
【问题描述】:

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

创建动作

@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

当我想第一次提交表单时,验证工作正常,但是当我保存然后尝试提交时,验证仅适用于申请人和伴奏模型,但不适用于照片和视频。申请人有_one 伴奏和has_many 照片和视频。问题出在更新中,但我不知道为什么。

【问题讨论】:

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


    【解决方案1】:

    在你的 update 方法中试试这个:-

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

    【讨论】:

    • 感谢您的回复,但我认为您没有做好。跳过验证部分在更新和创建中工作正常。我的问题是,当 if!params[:submit_button].blank 什么时候验证不起作用?为真,应进行验证。
    【解决方案2】:

    我设法通过添加解决了这个问题

    validates_associated :children 为模型。

    现在一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多