0

所以我尝试构建一个由两个模型的字段组成的表单。不幸的是,验证只适用于其中之一,尽管它们是相同的。

  • 如果第一个字段中有白色符号,控制台会显示红色“回滚”并且视图会显示错误。
  • 如果第二个字段中有一个白色标志,一切正常,呈现下一页,没有显示错误,但该值未保存。

综上所述:验证对两者都有效,但仅在第一次出现时抛出错误和回滚。此外,我正在使用 wicked form Wizard gem。
我的模型是:
candidate.rb

class Candidate < ApplicationRecord
  belongs_to :user
  has_one :candidate_form
  has_one :employee_form
  accepts_nested_attributes_for :candidate_form
  accepts_nested_attributes_for :employee_form
end

候选人表格.rb

class CandidateForm < ApplicationRecord
  belongs_to :candidate
  validates_format_of :name, without: /\W/, allow_blank: true
end

employee_form.rb (如您所见,它与candidate_form.rb 相同)

class EmployeeForm < ApplicationRecord
  belongs_to :candidate
  validates_format_of :pesel, without: /\W/, allow_blank: true
end

控制器:

def show
    @candidate = current_user.candidate
    render_wizard
  end

  def update
    @candidate = current_user.candidate
    @candidate.attributes = candidate_params
    render_wizard @candidate
  end

private

  def candidate_params
    params.require(:candidate).permit(candidate_form_attributes: [:id, :name],
                                      employee_form_attributes: [:id, :pesel])
  end

我的表单结构

<%= form_for @candidate, url: wizard_path, method: "put" do |f| %>
    <%= f.fields_for :candidate_form do |cand| %>
        <%= cand.text_field :name %>
    <% end %>
    <%= f.fields_for :employee_form do |emp| %>
        <%= emp.text_field :pesel %>
    <% end %>
    <%= f.submit "NEXT" %>
<% end %>

最后一个澄清什么不起作用:

  • “带空格的名称” - 字段中这样的字符串 :name 防止保存表单,引发错误,提供回滚
  • “带空格的 Pesel” - 字段中这样的字符串:pesel 不会阻止保存表单(仅此字段不保存)并且不会发生回滚
4

1 回答 1

0

哦,没关系。:pesel 是数据库中的整数类型。将其更改为字符串使一切正常。

于 2020-02-19T12:26:36.230 回答