Reputation: 2435
So I have many polymorphic children for a Profile object. The models are designed to destroy after_save if the specific Object's field is blank.
But for accept_nested_attributes I don't want to create the child object in the first place if it's blank. But if I leave the reject_if statement then the user no longer has the ability to empty the field on UPDATE because the reject_if rejects their blank input.
accepts_nested_attributes_for :socials, reject_if: proc { |att| att['username'].blank? }
accepts_nested_attributes_for :phones, reject_if: proc {|att| att['number'].blank? }
accepts_nested_attributes_for :websites, reject_if: proc {|att| att['url'].blank? }
So I want to reject_if: { ... }, on: :create
. But that doesn't seem to work.
Upvotes: 6
Views: 12866
Reputation: 1055
You can create a method and instead of sending a proc into the reject_if
option, which is the same, it is just more readable, so the code would look like:
accepts_nested_attributes_for :socials, reject_if: :social_rejectable?
private
def social_rejectable?(att)
att['username'].blank? && new_record?
end
You can just repeat the methods and then clean it up with some metaprogramming or add the new_record?
method on the proc
accepts_nested_attributes_for :socials, reject_if: proc { |att| att['username'].blank? && new_record?}
Upvotes: 14