ActiveRecord
does support this type of inheritance . For this to work first we have to add an attribute type para
the Pessoa
template. Creating this table would look something like this:
rails g model Pessoa nome cpf cnpj type
Ceito this is enough to create the two classes that inherit from Pessoa
# app/models/pessoa_fisica.rb
class PessoaFisica < Pessoa
end
and
# app/models/pessoa_juridica.rb
class Juridica < Pessoa
end
All models now have access to the same table. If you use the Pessoa
class, ActiveRecord
will always return all rows in this table, but if you use PessoaFisica
or PessoaJuridica
it will only treat records with the specified type. It is worth both insertion and recovery.
Validation can then be placed on each model separately, I suggest you extract this validation to a custom validator
, outside the template file.
In the country
PessoaFisica.create(cpf: '111.222.333-44')
=> #<PessoaFisica id: 1, nome: nil, cpf: "111.222.333-44", cnpj: nil, type: "PessoaFisica", created_at: "2016-07-16 17:03:29", updated_at: "2016-07-16 17:03:29">
PessoaJuridica.create(cnpj: '78.425.986/0036-15')
=> #<PessoaJuridica id: 2, nome: nil, cpf: nil, cnpj: "78.425.986/0036-15", type: "PessoaJuridica", created_at: "2016-07-16 17:04:13", updated_at: "2016-07-16 17:04:13">
Pessoa.all
=> #<ActiveRecord::Relation [#<PessoaFisica id: 1, nome: nil, cpf: "111.222.333-44", cnpj: nil, type: "PessoaFisica", created_at: "2016-07-16 16:53:59", updated_at: "2016-07-16 16:53:59">, #<PessoaJuridica id: 2, nome: nil, cpf: nil, cnpj: "78.425.986/0036-15", type: "PessoaJuridica", created_at: "2016-07-16 17:04:13", updated_at: "2016-07-16 17:04:13">]>
PessoaFisica.all
=> #<ActiveRecord::Relation [#<PessoaFisica id: 1, nome: nil, cpf: "111.222.333-44", cnpj: nil, type: "PessoaFisica", created_at: "2016-07-16 16:53:59", updated_at: "2016-07-16 16:53:59">]>
PessoaJuridica.all
=> #<ActiveRecord::Relation [#<PessoaJuridica id: 2, nome: nil, cpf: nil, cnpj: "78.425.986/0036-15", type: "PessoaJuridica", created_at: "2016-07-16 17:04:13", updated_at: "2016-07-16 17:04:13">]>