ruby on rails - How to delete child during update with reject_if option for accepts_nested_attributes_for -


i on rails 5.0. i'm not quite sure if should work or if need take different approach. have models procedure , complication procedure has_many complications defined so;

class procedure < activerecord::base   has_many :complications, dependent: :destroy   accepts_nested_attributes_for :complications, allow_destroy: true, reject_if: proc{|attr| attr[:name] == 'none'} end  class complication < activerecord::base   belongs_to :procedure   validates :name, presence: true end 

the user presented nested form procedure multiple complications. have used cocoon gem dynamically. on new record user presented empty complication select box. if leave empty validation fails. force them select 'none' in order prevent them skipping field. if select 'none' no complication added because of reject_if option. of works expected.

the problem have arises if complication selected (e.g. 'failed') , procedure record subsequently edited. if complication changed 'none' , record updated, complication left unchanged (i.e. still 'failed') when behaviour want complication destroyed.

presumably reject_if option doesn't function delete record on update if exists. correct? if so, appropriate way of handling case?

tia.

what want kind of out of scope reject_if option.

you should able functionality altering whitelisted params add _destroy = '1' if name "none" (or blank or nil).

class proceedurescontroller    # ...    def update    end    private     # ...     # allow trusted parameter "white list" through.     def proceedure_params       params.require(:proceedure)             .permit(:name,complications_attributes: [:id, :name, :_destroy])     end      def update_params       proceedure_params.tap |p|          p["complications_attributes"].each |a|            if a[:id].present? &&  ["none", nil, ""].includes?(a[:name])              a[:_destroy] = '1'            end          end        end     end end 

class procedure < activerecord::base   has_many :complications, dependent: :destroy   accepts_nested_attributes_for :complications,      allow_destroy: true,      reject_if: :reject_attributes_for_complication?    def self.reject_attributes_for_complication?     return false if attr[:_destroy]     attr[:name] == 'none'   end end 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -