简体   繁体   中英

How to validate existence of parent id in child model in Rails for nested attributes

Here are 2 models. Order takes nested attributes for 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? With nested_attributes, the existence of order_id in order_item is enforced already. However when saving an order_item on its own (not along with order ), we still need to validate the 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:

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:

class OrderItem
   belongs_to :order, inverse_of: :order_items
   # ... the rest
end

More about using inverse_of option with associations can be read here .

This:

validates :order_id, :presence => true

will only make sure that some value for order_id was submitted. You want this:

validates :order, :presence => true

That will make sure that an order with the submitted order_id exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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