【问题标题】:Ruby on Rails - Losing form values after failed validation on some fieldsRuby on Rails - 在某些字段验证失败后丢失表单值
【发布时间】:2021-02-06 08:13:20
【问题描述】:

我有一个表格

     <%= f.input :firstname, :label => "Forename", :input_html => { :placeholder => "Forename"} %>
     <%= f.input :surname, :label => "Surname", :input_html => { :placeholder => "Surname", :"data-

  <%= f.input :publiclyfundedteaching, :label => "Publicly funded teaching (PFT)", :input_html => {:style => 'width:7%', :id => "publiclyfundedteaching", :value => '0', :onkeyup => "myFunction()"} %>

  <%= f.input :non_publicly_funded_teaching, :label => "Non-Publicly Funded teaching (NPFT)", :input_html => {:style => 'width:7%', :id => "non_publicly_funded_teaching", :value => '0', :onkeyup => "myFunction()"} %>

和控制器

def create


@submission = Submission.new(submission_params)
@email = @submission.email
puts @email
if @submission.save
  flash[:notice] = 'Your user was successfully created.'
  
  else

@staffform = Form.find(10000)
   @livestatus = @staffform.status
   puts @staffform.status
   puts "not saved"

  puts @submission.errors.full_messages
render :new
  end

和型号:

validates :firstname, presence: true
validates :surname, presence: true
validates :email, presence: true


validates :total, numericality: { only_integer: true, equal_to: 100}


# First group

validates :publiclyfundedteaching, numericality: { only_integer: true }
validates :non_publicly_funded_teaching, numericality: { only_integer: true }
validates :support_for_teaching, numericality: { only_integer: true }

问题是 :publiclyfundedteaching、non_publicly_funded_teaching 和 support_for_teaching 的教学字段在验证后不保留这些值。电子邮件、姓氏和名字都可以。

请告诉我如何解决这个问题。 我猜这与这些字段的 value 属性有关?

非常感谢!!

【问题讨论】:

  • 您能告诉我们submission_params 在创建新记录之前是什么样子的吗?选项only_integer: true 根据正则表达式检查字段 /\A[+-]?\d+\z/ 请注意,“2”会匹配,但“2.0”不会。
  • 感谢您的回复,请参阅下面的评论

标签: ruby-on-rails validation


【解决方案1】:

submission_params 你可能有类似的东西:

def submission_params
  params.require(:your_model_name).permit(:firstname, :surname, :email)
end

这会删除任何其他字段以保护它们免受客户端伪造的数据的影响

如果您希望字段可写 - 将其添加到允许

【讨论】:

  • 非常感谢!我可能没有正确解释问题。本质上,当验证启动并显示表单错误消息时,:firstname、:surname、:email 的字段值仍然存在,但我们丢失了用户为数字字段输入的其他值。可能是由于最初与这些字段关联的 value 属性。
【解决方案2】:

查看:publiclyfundedteaching:non_publicly_funded_teaching 的表单字段中的:value =&gt; '0' (您提到的第三个不在您的表单中)。 即使您重新加载以前填写的表格,他们也会将字段中的值设置为 0。您可以删除它或尝试添加这样的 if 语句(假设提交是模型):

<%= f.input :publiclyfundedteaching, label: "Publicly funded teaching (PFT)", input_html: { style: 'width:7%', id: "publiclyfundedteaching", value: @submission.publiclyfundedteaching || 0, onkeyup: "myFunction()" } %>

【讨论】:

  • 非常感谢克拉拉。非常感激。正是我需要的
  • 不客气,如果你能接受我的回答,我会很高兴!
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多