繁体   English   中英

如何验证Rails中子模型中是否存在嵌套属性的父ID

[英]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_itemorder_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_idorder

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM