这里有 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_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
选项与关联可以阅读here .
关于ruby-on-rails - 如何验证 Rails 中子模型中嵌套属性的父 ID 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809265/