Bruno
Bruno

Reputation: 45

Rails custom validation inside model which belongs_to another

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:

I have 3 models:

Class User < ApplicationRecord
has_many :animals

Class Animal < ApplicationRecord
belongs_to :user
belongs_to :tipo

Class Tipo < 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

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.

So i think i must to get the user id and sum his respectively animals.mensal_cost array

Ok now u're contextualized, ill set my code below. PS. it's inside animal model:

#Want to get the total of a single user mensal cost
def total
  user_id.each do |mensal_cost|
  mensal_cost.inject(&:+)
end

#Now the custom validation itself

validate :check_mtotal

  def check_mtotal
    if user_id && total > 1000
    errors.add(:user_id, message: 'cant add more animals')
  end
end

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.

second... i need the first problem solve to test the second :(.

anyone can help with this?

Thank you very much for your attention

Upvotes: 0

Views: 546

Answers (1)

Bruno
Bruno

Reputation: 45

Well i figured out the solution and it's below:

User model
#Returns the total mensal cost
def max_mensal
  animals.sum(:mensal_cost)
end

Animal model
#Validates the mensal ammount

validate :check_form_mammount

def check_for_mammount
  if user_id && user.max_mensal > (value here)
  errors.add(:mensal_cost, message: 'msg here')
end

Upvotes: 1

Related Questions