Rails:验证关联数

时间:2014-04-24 02:25:45

标签: ruby-on-rails ruby ruby-on-rails-3 has-many-through

如何为外部定义的多个关联编写验证?我到目前为止写的是这样的:

class Document
  validate :publication_count

  private

  def publication_count
    if publications.count > template.component_count
      errors.add(:articles, 'too many')
    elsif publications.count < template.component_count
      errors.add(:articles, 'not enough')
    end
  end

publicationstemplate都是关联。我刚刚收到此代码的回滚错误,即使该记录应该有效。

1 个答案:

答案 0 :(得分:1)

您的代码显示正确,因此似乎没有正确设置或保存关联。

你检查过:

    在保存之前,
  • publicationstemplate都已分配到Document实例?
  • 回滚错误不是出于其他原因,例如唯一性失败?
  • 这是实际的验证失败而不是另一个?