[英]How to validate existence of parent id in child model in Rails for nested attributes
Here are 2 models.这里有2个模型。
Order
takes nested attributes for order_items
. Order
采用order_items
嵌套属性。
class order
has_many order_items
accept_nested_attributes_for :order_items
end
class order_item
belongs_to :order
validates :order_id, :presence => true #this line cause spec failure.
end
How to validates existence of order_id
in order_item
model?如何验证
order_item
模型中order_id
存在? With nested_attributes, the existence of order_id
in order_item
is enforced already.使用nested_attributes,
order_item
中order_id
的存在已经被强制执行。 However when saving an order_item
on its own (not along with order
), we still need to validate the order_id
.但是,当
order_item
保存order_item
时(而不是与order
一起保存),我们仍然需要验证order_id
。
If I get it right you have trouble saving associated records with your setup:如果我做对了,您将无法保存与您的设置相关的记录:
params = {number: 'order-123', order_items_attributes:{product_id:1, quantity: 2, price: 3}}
Order.create params # => this should not work
To fix it, you need to tell Rails explicitly about associations, using inverse_of
option:要修复它,您需要使用
inverse_of
选项明确地告诉 Rails 关联:
class Order
# without inverse_of option validation on OrderItem
# is run before this association is created
has_many :order_items, inverse_of: :order
accepts_nested_attributes_for :order_items
end
It's not required in your case but your can add inverse_of
in OrderItem
as well:在您的情况下不需要,但您也可以在
OrderItem
添加inverse_of
:
class OrderItem
belongs_to :order, inverse_of: :order_items
# ... the rest
end
More about using inverse_of
option with associations can be read here .可以在此处阅读有关将
inverse_of
选项与关联一起使用的更多信息。
This:这个:
validates :order_id, :presence => true
will only make sure that some value for order_id
was submitted.只会确保提交了
order_id
某些值。 You want this:你要这个:
validates :order, :presence => true
That will make sure that an order
with the submitted order_id
exists.这将确保存在提交的
order_id
的order
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.