ActiveRecord still save parent object if validations on children fail
With a relationship setup like:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
validates_presence_of :first开发者_运维百科_name
end
p = Parent.new
p.children.build
p.save
=> false
p.errors
=> {:children => ["is invalid"]}
Is there a way to keep the validations on the child object, but not have their failed validation block the save of the parent?
Take a look at save(options={})
in ActiveRecord::Validations
.
You can pass in :validate => false
to save(), which will skip the call to valid?
.
This will also skip any validations on the parent object, so you may have to do something more involved if the parent has validations as well.
Source
It's not rails style, but it answers your question. So just manage association by yourself:
p = Parent.new
p.save
c = Children.new(:parent_id => p.id)
c.save => 'first name can't be blank"
精彩评论