Reputation: 8511
My form lets you create a "child" on the same form as the parent, by entering that kid's name.
I only want to save the child record if a name was provided. In other words, I don't want to save a child with a blank name. I only want to create the child object if a name was provided.
What's a good way to do that?
Upvotes: 0
Views: 61
Reputation: 5839
According to docs:
:reject_if
Allows you to specify a Proc or a Symbol pointing to a method that checks whether a record should be built for a certain attribute hash. The hash is passed to the supplied Proc or the method and it should return either true or false. When no :reject_if is specified, a record will be built for all attribute hashes that do not have a _destroy value that evaluates to true. Passing :all_blank instead of a Proc will create a proc that will reject a record where all the attributes are blank excluding any value for _destroy.
So, we need to:
class Parent < ActiveRecord::Base
has_many :kids
accepts_nested_attributes_for :kids, :reject_if => proc { |attributes| attributes[:name].blank? }
end
Upvotes: 1