Radek
Radek

Reputation: 23

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.

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:

Upvotes: 0

Views: 37

Answers (1)

Radek
Radek

Reputation: 23

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

Upvotes: 0

Related Questions