Rails: use REJECT_IF only for the CREATE action for nested attributes

So I have a lot of polymorphic children for the Profile object. Models are designed to destroy after_save if a particular Object field is empty.

But for accept_nested_attributes, I don't want to create a child if it is empty. But if I leave the reject_if statement, the user can no longer clear the field in the UPDATE because reject_if rejects their empty 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 it doesn't work.

+3


source to share


1 answer


You can create a method and instead of sending a proc to a parameter reject_if

, which is the same, it will be more readable, so the code will look like this:

accepts_nested_attributes_for :socials, reject_if: :social_rejectable?

private

 def social_rejectable?(att)
  att['username'].blank? && new_record?
 end

      



You can just iterate over the methods and then clean it up with some metaprogramming, or add a method new_record?

toproc

accepts_nested_attributes_for :socials, reject_if: proc { |att| att['username'].blank? && new_record?}

      

+7


source







All Articles