【问题标题】:Rails Validation: need to validate all objects in associated collection but each object saves one at a timeRails 验证:需要验证关联集合中的所有对象,但每个对象一次保存一个
【发布时间】:2014-02-23 11:33:59
【问题描述】:

我有以下关联:

class Budget < ActiveRecord::Base
  has_many :budget_components
end

class BudgetComponent < ActiveRecord::Base
  belongs_to :budget
end

当我将budgetbudget_component 对象集合保存在budget_component needs to be validated such that all of thebudget'sbudget_component'srevenue_percentagefields add up to1.0 中的一个字段(我们称之为revenute_precentage)(例如都必须等于 100%)。

我预计会发生的问题是数据库可能会一次验证一个或将一个未保存的记录与已保存的记录进行比较,并且应该有效的内容可能会失效。

我是否应该在 budget 对象上添加一个验证器来验证 budget_components 还是这样就可以了?

【问题讨论】:

  • 你可以在你的 budget.rb 中添加一个 before_save 回调

标签: ruby-on-rails validation nested-attributes


【解决方案1】:

我会亲自向BudgetComponent 模型添加一个验证器,并通过accepts_nested_attributes_for 传递数据,如下所示:

class Budget < ActiveRecord::Base
  has_many :budget_components
  accepts_nested_attributes_for :budget_components
end

class BudgetComponent < ActiveRecord::Base
  belongs_to :budget

  validates :your, :attributes,
     presence: { message: "Can't be blank!" }
end

这意味着当您将参数从表单传递到模型时,它将单独验证集合的每个成员

您必须使用nested forms 才能使其正常工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2023-03-23
    • 2013-04-07
    • 1970-01-01
    相关资源
    最近更新 更多