Doubt Rails Relationship

6

I'm learning Rails yet, and I'm doubtful if I'm doing it right. I have a Animal Table and a Reproduction table, each animal can have one or more reproductions and each two Animals (Father and Mother) each reproduction can generate one or more animals.

No Animal model:

  belongs_to :reproduction

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

No Playback model:

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

  validates :mother, presence: true

I think I'm doing wrong, something, the parent field and the parent field should be in Reproduction being key strangles of the Animal table.     

asked by anonymous 03.07.2016 / 20:30

1 answer

4

So you described the correct modeling would be:

No Animal model:

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 children, regardless of whether you are a parent.

No Playback model:

  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 parent field and the parent field should be in Reproduction being key strangles of the Animal table.

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
    
04.07.2016 / 16:05