Rails 模型内部的自定义验证 belongs_to 另一个

Rails custom validation inside model which belongs_to another

我正在尝试学习 ruby 并尝试通过活动记录方法使用业务规则和控制台。 这是我现在面临的问题,假设以下情况:

我有 3 个模型:

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

我想进行验证,得到 user_id 并对 mensal_cost 求和 他所有的动物,所以如果这个成本高于 1000 那么他不能有更多的动物。

所以我认为我必须获取用户 ID 并分别对其求和 animals.mensal_cost 数组

好的,现在你已经了解情况了,我将在下面设置我的代码。 PS。在动物模型里面:

#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

好吧,第一个问题是我的总数没有返回任何东西,所以我真的不知道如何让它继续获得单个用户的 mensal_cost 数量。

第二...我需要解决第一个问题来测试第二个问题:(.

有人可以帮忙吗?

非常感谢您的关注

好吧,我找到了解决方案,如下所示:

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