是否可以在迁移级别禁止两个变量之一的 'null'?
Is it possible to disallow 'null' for either one of two variables at the migration level?
Author
属于一篇文章或一本书,绝不属于两者。在 Author 的迁移文件中,我有:
t.references :article, index: true
t.references :book, index: true
在模型文件中:
validate :article_or_book_id
def article_or_book_id
if article_id.present? && book_id.present?
errors.add(:article_id, "An author has to have either a book or article")
elsif !article_id.present? && !book_id.present?
errors.add(:article_id, "This author has no article nor a book")
end
end
问题:如何将 :article
或 :book
不能是 null
的迁移文件添加到迁移文件中?
使用 polymorphic association
怎么样?
教程如下:
Author
属于一篇文章或一本书,绝不属于两者。在 Author 的迁移文件中,我有:
t.references :article, index: true
t.references :book, index: true
在模型文件中:
validate :article_or_book_id
def article_or_book_id
if article_id.present? && book_id.present?
errors.add(:article_id, "An author has to have either a book or article")
elsif !article_id.present? && !book_id.present?
errors.add(:article_id, "This author has no article nor a book")
end
end
问题:如何将 :article
或 :book
不能是 null
的迁移文件添加到迁移文件中?
使用 polymorphic association
怎么样?
教程如下: