Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: use REJECT_IF only on CREATE action for nested attributes

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.

like image 438
6ft Dan Avatar asked Dec 26 '14 18:12

6ft Dan


1 Answers

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?}
like image 90
kurenn Avatar answered Nov 10 '22 15:11

kurenn