rails 4 验证关联对象 + 数据库约束
rails 4 validating associated object + db constraint
我正在尝试向 rails 中的外键字段和 postgres 数据库中的约束添加验证。
假设有一个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方式:"When you’re trying to ensure that an association is present, pass validates_presence_of its foreign key attribute, not the association variable itself. Note that the validation will fail in cases when both the parent and child object are unsaved (since the foreign key will be blank)."
在这种情况下,如何在外键字段上实现模型验证和数据库约束?
在这种情况下,您只需在模型中创建自定义验证方法即可。
在Product
模型中写下如下验证方法,保证一个product
有product_features
.
validate :product_features
def product_features
product_features.present?
end
事实是,验证密钥本身的存在(例如 product_id
)是相当无用的,因为 @product_feature.product_id = -25
将通过验证。
我总是对关联进行存在验证:
validates :product, presence: true
无论您以何种方式创建对象,这都有效:
ProductFeature.new product: Product.new
...或...
Product.new product_features: [ ProductFeature.new ]
我不确定为什么有人会推荐其他任何东西,验证密钥本身并不能保证数据库中存在该密钥。
这不会直接回答您的问题,但是在使用嵌套表单时,您应该像这样构建对象:
Product.product_features.new
这样你就可以确定 product_id
在 product_feature
我正在尝试向 rails 中的外键字段和 postgres 数据库中的约束添加验证。
假设有一个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方式:"When you’re trying to ensure that an association is present, pass validates_presence_of its foreign key attribute, not the association variable itself. Note that the validation will fail in cases when both the parent and child object are unsaved (since the foreign key will be blank)."
在这种情况下,如何在外键字段上实现模型验证和数据库约束?
在这种情况下,您只需在模型中创建自定义验证方法即可。
在Product
模型中写下如下验证方法,保证一个product
有product_features
.
validate :product_features
def product_features
product_features.present?
end
事实是,验证密钥本身的存在(例如 product_id
)是相当无用的,因为 @product_feature.product_id = -25
将通过验证。
我总是对关联进行存在验证:
validates :product, presence: true
无论您以何种方式创建对象,这都有效:
ProductFeature.new product: Product.new
...或...
Product.new product_features: [ ProductFeature.new ]
我不确定为什么有人会推荐其他任何东西,验证密钥本身并不能保证数据库中存在该密钥。
这不会直接回答您的问题,但是在使用嵌套表单时,您应该像这样构建对象:
Product.product_features.new
这样你就可以确定 product_id
在 product_feature