Doubt Relationship Rails

Asked

Viewed 102 times

6

I’m learning Rails still, and I’m in doubt if I’m doing it right. I have a Table Animal and a table Reproduction, each animal may have one or more reproductions and each reproduction will only have two Animals (Father and Mother) each reproduction can generate one or more animals.

In the model of Animal:

  belongs_to :reproduction

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

In the model Reproduction:

  belongs_to :father, class_name: "Animal"
  belongs_to :mother, 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.

1 answer

4


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

  • 1

    Good show that worked @Andrégava :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.