respond_to show errors with relationships

Asked

Viewed 156 times

1

My question is only about the architecture of how to return the error to view. Follow the example below:

    class Pessoa < ActiveRecord::Base
        belongs_to :responsavel, class_name: 'Pessoa',  foreign_key: 'responsavel_id'
    end

    class Alunos < Pessoa
    end

With these models, I have the following form

. <%= form_for @aluno, html: {role: 'form', class: 'form-horizontal', :'data-turbo-form' => 'true'} do |f| %> <%= render partial: 'people/form', locals: {f: f} %>

Fill out the details of the person responsible for this student.

Responsible <%= f.fields_for(:responsable, @pupil.responsable) do |responsible| %> <%= responsibly.hidden_field :id, value: @aluno.responsavel.id unless @aluno.responsavel.nil? %> <%= render partial: 'people/form', locals: {f: responsible} %> <% end %> <% end %> .

The form pessoas/form is a partial view that is shared among other views.

That way, every request is made to Aluno#create and I do the following:

class AlunosController < ApplicationController
    def create
        @aluno = Aluno.new(aluno_params)

        # e se aqui o model parar nas validações definidas? Como eu gerenciaria os erros do responsavel?
        set_responsavel responsavel_params

        respond_to do |format|
            # adiciono várias outras checagens aqui nessa condição para ver se o model responsável possui errros?
            if @aluno.save
                format.html { redirect_to alunos_path }
                format.json { render action: 'show', status: :created, location: @aluno }
            else
                format.html { render action: 'new' }
                # como eu varia o merge dos erros do responsável com o erro do aluno? responsavel.errors << @aluno.erros?
                format.json { render json: @aluno.errors, status: :unprocessable_entity }
            end
        end
    end

    def create_responsavel(params)
        responsavel = Pessoa.create params
    end

    def update_responsavel(params)
        responsavel = Pessoa.update params[:id], params
        responsavel
    end

    def set_responsavel(resp_params)
        unless resp_params[:nome].nil?
            responsavel = (resp_params[:id].nil? && create_responsavel(resp_params)) || update_responsavel(resp_params)
            @aluno.responsavel_id = responsavel.id unless responsavel.blank?
        end
    end
end

That way, I create the responsible one first and then I update him on the student. The point is, if I try to save the responsible one first and make a mistake, how do I merge the errors of the responsavel with the mistakes of @aluno?

There won’t just be the relationship responsavel with the Student, in the future Nota and Matricula. I believe I have to follow the same line of reasoning for other relationships, right?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.