Rails 4.0 Strong Parameters nested attributes with a key that points to a hash

后端 未结 6 1477
生来不讨喜
生来不讨喜 2020-12-01 00:43

I was playing around with Rails 4.x beta and trying to get nested attributes working with carrierwave. Not sure if what I\'m doing is the right direction. After searching

6条回答
  •  余生分开走
    2020-12-01 01:17

    Sanitize before save in controller Sanitize accepts_nested_attributes_for attributes with index.

    before_action :sanitize_fields_params, :only => [:create, :update]
    
    def sanitize_fields_params
    
        product_free_shippings_attributes = params[:product][:product_free_shippings_attributes]
    
        product_free_shippings_attributes.each do |index, key_value|
          params[:product][:product_free_shippings_attributes]["#{index}"][:weight] = clear_decimal(key_value[:weight])
          params[:product][:product_free_shippings_attributes]["#{index}"][:height] = clear_decimal(key_value[:height])
          params[:product][:product_free_shippings_attributes]["#{index}"][:width] = clear_decimal(key_value[:width])
          params[:product][:product_free_shippings_attributes]["#{index}"][:depth] = clear_decimal(key_value[:depth])
        end
     end
    
     def clear_decimal(field) 
        return (field.to_s.gsub(/[^\d]/, '').to_d / 100.to_d) unless field.blank?
      end
    

提交回复
热议问题