Search code examples
ruby-on-railsvalidationactiverecordnested-attributeswicked-gem

Validation of multiple models in one, using Nested Atrributes


So i tried to build a form consisted of fields from two models. Unfortunately, validation only works for one of them, despite they are the same.

  • If there is a white sign in first field, console shows red "rollback" and view shows the error.
  • If there is a white sign in second field, everything goes as normal, the next page is rendered, no error is shown, YET the value is not saved.

So to sum up: validation works on both, but throws errors and rollbacks only in case of first. On addition, I am using the wicked form wizard gem.
My models are:
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

candidate_form.rb

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

employee_form.rb (as you can see, its the same as candidate_form.rb)

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

controller:

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

my form structure

<%= 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 %>

One last clarification what doesn't works:

  • "Name with a space" - string like this in field :name prevents the form from being saved, throws an error, provides a rollback
  • "Pesel witha a space" - string like this in field :pesel DOES NOT prevent the form from being saved (only this field is not saved) and the rollback doesn't occur

Solution

  • Oh, nevermind. The :pesel was of type integer in database. Changing it to string makes everything works perfectly.