Rails嵌套属性验证强制首先保存父项

时间:2018-10-30 14:15:21

标签: ruby ruby-on-rails-5

我有2种型号,例如:

class Father < ActiveRecord::Base
    has_many :children
    accepts_nested_attributes_for :children
end



class Child < ActiveRecord::Base
    belongs_to :father
    validate :validate_money

    def validate_money
      children = Child.where(id: self.father.id)
      sum_of_children_pocket_money = my_func # function for getting sum of all pocket money of all children
      if sum_of_children_pocket_money > self.father.money
        errors.add(:pocket_money, "My error message!!!")
      end
    end
  end

最初我有:

,并在通过passengers_attributes时更新客户(id = 1),例如

{
  id: 1,
  name: "Father 1",
  money: 1000,
  children: [
    {
      name: "Child 1",
      id: 1,
      pocket_money: 500
    }
  ]
}

然后我要发送更新:

{
  id: 1,
  name: "Father 1",
  money: 2000,
  children: [
    {
      name: "Child 1",
      id: 1,
      pocket_money: 1500
    }
  ]
}

所以我在验证中出错,因为它开始进行sum_of_children_pocket_money > self.father.money比较,并且sum_of_children_pocket_money等于1500,但self.father.money仍然是1000。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

将验证逻辑从“儿童”转移到“父亲”应该可以解决问题。

class Father < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children
  validate :validate_money

  def validate_money
    children = Child.where(id: id)
    sum_of_children_pocket_money = my_func # function for getting sum of all pocket money of all children
    if sum_of_children_pocket_money > money
      errors.add(:pocket_money, "My error message!!!")
    end
  end
end



class Child < ActiveRecord::Base
  belongs_to :father
end