respond_to show errors with relationships

1

My question is just about the architecture of how to return the error for view. Here's 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

.     

asked by anonymous 26.02.2014 / 02:20

1 answer

0

You need to add accepts_nested_attributes_for :responsavel to your model Aluno

And in your form, you only need to do the following:

form_for @aluno do |f|
  ...

  f.fields_for :responsavel do |r|
  ...

In your Alunos_Controller

def new
  @aluno = Aluno.new
  @aluno.build_responsavel
end

And @aluno.save should already care about creating the dependency of the responsible and adding the errors needed to show in the view.

In order not to create a duplicate, you can create a hook before_save in your student and check if the responsible exists, if it exists, use it instead of creating another one.

I hope this helps.

    
26.02.2014 / 07:39