For what he described the correct modeling would be:
In the model of 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: I’ve added a Reproductions method, in case you want to bring all your children, regardless of whether you’re a parent or a parent.
In the model Reproduction:
belongs_to :father, foreign_key: "father_id", class_name: "Animal"
belongs_to :mother, foreign_key: "mother_id", class_name: "Animal"
validates :mother, presence: true
I think I’m doing wrong, something, The father camp and mother camp should be in Reproduction and are table foreign keys Animal.
Result is something like:
> 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
Thanks so much for the help, it worked :D
– André Gava
Good show that worked @Andrégava :D
– Luiz Carvalho