![](/img/trans.png)
[英]Ruby on Rails - nested attributes: How do I access the parent model from child model
[英]How to validate existence of parent id in child model in Rails for nested attributes
这里有2个模型。 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
如何验证order_item
模型中order_id
存在? 使用nested_attributes, order_item
中order_id
的存在已经被强制执行。 但是,当order_item
保存order_item
时(而不是与order
一起保存),我们仍然需要验证order_id
。
如果我做对了,您将无法保存与您的设置相关的记录:
params = {number: 'order-123', order_items_attributes:{product_id:1, quantity: 2, price: 3}}
Order.create params # => this should not work
要修复它,您需要使用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
在您的情况下不需要,但您也可以在OrderItem
添加inverse_of
:
class OrderItem
belongs_to :order, inverse_of: :order_items
# ... the rest
end
可以在此处阅读有关将inverse_of
选项与关联一起使用的更多信息。
这个:
validates :order_id, :presence => true
只会确保提交了order_id
某些值。 你要这个:
validates :order, :presence => true
这将确保存在提交的order_id
的order
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.