title: Rails custom validation inside model which belongs_to another
body: <p>i'm trying to learn ruby and trying to work with business rules and console through active record methods.
  Here's the problem i'm facing right now, assume the following scenario:</p>
  
  <p>I have 3 models:</p>
  
  <pre><code>Class User &lt; ApplicationRecord
  has_many :animals
  
  Class Animal &lt; ApplicationRecord
  belongs_to :user
  belongs_to :tipo
  
  Class Tipo &lt; ApplicationRecord
  has_many :animals
  
  respective migration:
  User
  t.string :name
  t.string :doc
  t.date   :birth_day
  
  Animal
  t.string  :name
  t.decimal :mensal_cost
  
  add_index :animals, :user_id
  add_index :animals, :user_id
  
  Tipo 
  t.string :tipo_animal
  </code></pre>
  
  <p>I want to make a validation which get the the user_id and sum the mensal_cost
  of all his animals,  so if this cost is higher than 1000 then he cant have more animals.</p>
  
  <p>So i think i must to get the user id and sum his respectively animals.mensal_cost array</p>
  
  <p>Ok now u're contextualized, ill set my code below.
  PS. it's inside animal model:</p>
  
  <pre><code>#Want to get the total of a single user mensal cost
  def total
    user_id.each do |mensal_cost|
    mensal_cost.inject(&amp;:+)
  end
  
  #Now the custom validation itself
  
  validate :check_mtotal
  
    def check_mtotal
      if user_id &amp;&amp; total &gt; 1000
      errors.add(:user_id, message: 'cant add more animals')
    end
  end
  </code></pre>
  
  <p>Well, first problem is that my total isn't returning anything, so i really don't know how make it proceed to get the ammount of mensal_cost of a single user. </p>
  
  <p>second... i need the first problem solve to test the second :(.</p>
  
  <p>anyone can help with this?</p>
  
  <p>Thank you very much for your attention</p>