验证与before_add回调的自关联

时间:2016-02-11 23:44:02

标签: ruby-on-rails validation associations

我有一个模型Todo,带有自我引用的父母和孩子

has_and_belongs_to_many :children, class_name: "Todo", join_table: "todos_todos", foreign_key: "parent_id", association_foreign_key: :child_id
has_and_belongs_to_many :parents, class_name: "Todo", join_table: "todos_todos", foreign_key: "child_id", association_foreign_key: :parent_id

我想对它们两者执行before_add之类的操作会产生验证错误。我已尝试before_add: [:parent_due_after_or_on_self]

def parent_due_after_or_on_self(parent)
    if parent.due < self.due 
        self.errors.add(:parents, "Parent cannot be due before child")
    end 
end 

但这没有任何作用。我已经尝试在添加错误后立即添加raise "Parent cannot be due before child",这会让我收到错误消息,但现在我无法挽救它以将用户返回到表单以修复错误。我是积极的我本周早些时候就开始工作了,但是我已经丢失了代码并且无法记住它的确切含义。

1 个答案:

答案 0 :(得分:0)

@ meagar♦写道 Rails 4 HABTM custom validation on associations,没有有效的方法可以对HABTM关联使用验证。

在我看来,最好的选择是使用has_many :through =>,并使用您的连接模型(在您的情况下 TodosTodo )进行验证。

相关问题