【发布时间】:2016-03-09 19:39:06
【问题描述】:
我正在尝试为 rails 中的外键字段和 postgres db 中的约束添加验证。
假设有一个user。 User has_many :products 和 product belongs_to :user。在这种情况下,情况很容易,因为用户是在添加新产品时确定的。所以validates: user, presence: true可以添加到product model中,user_id, null: false可以添加到postgres db中。
但是如果同时创建父子对象和对象呢?假设在 product form 我有 product_features 作为嵌套属性。所以product has_many :product_features 和product_feature belongs_to :product。
根据 Rails 4 Way:“当您尝试确保关联存在时,请传递其外键属性的 validates_presence_of,而不是关联变量本身。请注意,如果父子节点都存在验证将失败的情况对象未保存(因为外键为空白)。”
在这种情况下,如何实现模型验证和外键字段的数据库约束?
【问题讨论】:
标签: ruby-on-rails database postgresql validation constraints