I have a model Order
which is like
# app/models/order.rb
class Order< ApplicationRecord
has_one :detail
has_one :extra
..
end
I have two orders
order1 = Order.first
order1.detail #<OrderDetail:0x00 name: "abc", remark: 'test1'>
order1.extra #<OrderExtra:0x00 email: nil, recipent: nil>
order2 = Order.second
order1.detail #<OrderDetail:0x00 name: "abc", remark: 'test1'>
order1.extra #<OrderExtra:0x00 email: nil, recipent: "xyz">
When I call order1.valid?
or order1.save!
it will not check OrderExtra
validation and returns true. But when I call order2.valid?
or order2.save!
it checks OrderExtra
validation.
order1.save! # true
order2.save! # ActiveRecord Invalid OrderExtra
I want to know how rails checks if they want to check associated validation when call save!
and the reason behind that.
Please let me know if any additional requirement needed on this.
use the validates_associated
for enforcing associated model validations
class Book < ActiveRecord::Base
has_many :pages
belongs_to :library
validates_associated :pages, :library
end
This validation will not fail if the association hasn't been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validates_presence_of
.
class Library < ActiveRecord::Base
has_many :books
validates_presence_of :name
end
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.