Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle a :reject_if if a new record and not an update

I am working on some forms that involve uploading an image. There is a standard two forms to add and all the forms currently associated. It will look like this:

enter image description here

I have an assets class that is polymorphic for other classes involved (such as locations, items). The problem is that items can be uploaded or updated. For items and locations, I have the following:

accepts_nested_attributes_for :assets, :allow_destroy => true, :reject_if => lambda { |a| a[:asset].blank? } 

but this seems to reject if there is no uploaded file. This is essentially what we want if it is a new file but there are cases where we just update the description via the asset id. The above :reject_if will reject that scenario. How can I make an exception for updating this other type of information?

thx

like image 549
timpone Avatar asked Dec 07 '25 10:12

timpone


1 Answers

I solved it by adding a condition on params[:id] to the reject_if block. For your example, it would look like this:

accepts_nested_attributes_for :assets, :allow_destroy => true, 
    :reject_if => lambda { |a| a[:asset].blank? && a[:id].blank? }

Any existing records should come back with an id attribute in the nested hash, so this should allow updates to existing nested records while still allowing you to reject new records with no asset (because new records don't yet have an id).

like image 134
Nat Budin Avatar answered Dec 08 '25 23:12

Nat Budin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!