6

Estou aprendendo Rails ainda, e estou com dúvida se estou fazendo certo. Tenho uma Tabela Animal e uma tabela Reprodução, cada animal pode ter uma ou mais reproduções e cada reprodução terá somente dois Animais (Pai e Mãe) cada reprodução pode gerar um ou mais animais.

No model de Animal:

  belongs_to :reproduction

  has_many :animals, foreign_key: "mother_id", class_name: "Animal"
  has_many :animals, foreign_key: "father_id", class_name: "Animal"

No model Reprodução:

  belongs_to :father, class_name: "Animal"
  belongs_to :mother, class_name: "Animal"

  validates :mother, presence: true

Acho que estou fazendo errado, alguma coisa, O campo pai e campo mãe devem estar em Reprodução sendo que são chaves estrangerias da tabela Animal.

1 Resposta 1

4

Pelo que descreveu a modelagem correta seria:

No model de Animal:

class Animal < ActiveRecord::Base
  has_many :reproductions_as_father, class_name: 'Reproduction',  foreign_key: 'father_id'
  has_many :reproductions_as_mother, class_name: 'Reproduction',  foreign_key: 'mother_id'

  def reproductions
    Reproduction.where('mother_id = ? or father_id = ?', id, id)
  end
end

PS: Adicionei um método reproductions, caso você queira trazer todos os filhos, independente se é pai ou mãe.

No model Reprodução:

  belongs_to :father, foreign_key: "father_id", class_name: "Animal"
  belongs_to :mother, foreign_key: "mother_id", class_name: "Animal"

  validates :mother, presence: true

Acho que estou fazendo errado, alguma coisa, O campo pai e campo mãe devem estar em Reprodução sendo que são chaves estrangerias da tabela Animal.

Resultado é algo como:

> mae = Animal.create
> pai = Animal.create

> filho1 = Reproduction.new
> filho1.mother = mae
> filho1.father = pai
> filho1.save

> filho2 = Reproduction.new
> filho2.mother = mae
> filho2.save

> mae.reproductions_as_mother
=> #<ActiveRecord::Associations::CollectionProxy [#<Reproduction id: 2, father_id: 4, mother_id: 3, created_at: "2016-07-04 13:58:03", updated_at: "2016-07-04 13:58:17">, #<Reproduction id: 3, father_id: nil, mother_id: 3, created_at: "2016-07-04 13:58:55", updated_at: "2016-07-04 13:58:55">]>

> pai.reproductions_as_father
=> #<ActiveRecord::Associations::CollectionProxy [#<Reproduction id: 2, father_id: 4, mother_id: 3, created_at: "2016-07-04 13:58:03", updated_at: "2016-07-04 13:58:17">]> 

> filho1.father
 => #<Animal id: 4, created_at: "2016-07-04 13:57:03", updated_at: "2016-07-04 13:57:03">

 > filho1.mother
 => #<Animal id: 3, created_at: "2016-07-04 13:56:57", updated_at: "2016-07-04 13:56:57"> 

> filho2.mother
 => #<Animal id: 3, created_at: "2016-07-04 13:56:57", updated_at: "2016-07-04 13:56:57"> 
> filho2.father
 => nil
2
  • Muito obrigado pela ajuda, deu certo :D 7/07/2016 às 0:14
  • 1
    Show que bom que deu certo @AndréGava :D 7/07/2016 às 12:32

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .