【发布时间】:2010-11-09 23:42:04
【问题描述】:
我有两个 ActiveRecord 类。这些类的简化视图:
class Account < ActiveRecord::Base
has_many :user_account_roles
end
class UserAccountRole < ActiveRecord::Base
belongs_to :account
# Has a boolean attribute called 'administrator'.
end
我正在苦苦挣扎的是,我希望能够对此应用两个验证规则: * 确保最后一个 UserAccountRole 不能被删除。 * 确保不能删除作为管理员的最后一个 UserAccountRole。
我真的很难理解实现这种结构验证的最佳方法。我已经尝试向关联添加一个 before_remove 回调,但我不喜欢这必须抛出一个需要被控制器捕获的错误。我宁愿这被视为“只是另一个验证”。
class Account < ActiveRecord::Base
has_many :user_account_roles, :before_remove => check_remove_role_ok
def check_remove_relationship_ok(relationship)
if self.user_account_relationships.size == 1
errors[:base] << "Cannot remove the last user from this account."
raise RuntimeError, "Cannot remove the last user from this account."
end
end
end
我不认为这有什么不同,但我也在使用accepts_nested_attributes_for。
【问题讨论】:
标签: ruby-on-rails validation activerecord ruby-on-rails-3