0

Submitting the following parameters

Parameters: {[...] "physicalinventario"=>{[...] "physicalinventarioitems_attributes"=>{"0"=>{"quantity"=>",85"}}}, "commit"

The goal is to intercept the quantity parameter at the physicalinventarioitem controller create action, and sanitize it for possible comma as decimal value being input

if params[:physicalinventario][:physicalinventarioitems_attributes][:quantity].include? ","
  params[:physicalinventarioitem][:quantity] = params[:physicalinventario][:physicalinventarioitems_attributes][:quantity].tr!(',', '.').to_d
end

However, the syntax is wrong as no value after the comma is being handled.

Jerome
  • 5,583
  • 3
  • 33
  • 76

2 Answers2

1

@Alex answer is fine if you have only one quantity.

but what if you have multiple quantites,

eg: {"0"=>{"quantity"=>",85"},"1"=>{"quantity"=>",90"}}

So, here is the answer which also achieves that requirement for multiple nested attributes.

hash = {"physicalinventario"=>{"physicalinventarioitems_attributes"=>{"0"=>{"quantity"=>",85"},"1"=>{"quantity"=>",90"}}}}

The code that you require,

hash["physicalinventario"]["physicalinventarioitems_attributes"].each do |key, value|
    if value["quantity"].include? ","
    value["quantity"] = value["quantity"].tr!(',', '.').to_f
    end
end

Here is the resultant hash,

`{"physicalinventario"=>{"physicalinventarioitems_attributes"=>{"0"=>{"quantity"=>0.85}, "1"=>{"quantity"=>0.9}}}}`
Community
  • 1
  • 1
Sravan
  • 18,467
  • 3
  • 30
  • 54
  • @Jerome, please check this answer for multiple nested attributes. – Sravan Nov 25 '16 at 10:39
  • two observations. the first is that the code should be placed in the create action of the nesting record. Second, as stated, this is leading to a `no implicit conversion of String into Integer`error. `params[:physicalinventario][:physicalinventarioitems_attributes].each do |key, value|` will process properly. – Jerome Nov 25 '16 at 10:43
  • I used `to_f` there. – Sravan Nov 25 '16 at 10:46
0

Looks like you've missed ["0"] in the chain to get :quantity.

Should be

params[:physicalinventario][:physicalinventarioitems_attribu‌tes]["0"][:quantity]

Most convenient Rails way to sanitize(normalize) data in a model. To don't create duplicates, more here How best to sanitize fields in ruby on rails

Community
  • 1
  • 1
Alex Kojin
  • 5,044
  • 2
  • 29
  • 31
  • the sequence identifier in the chain being missed I agree with. However, the submission is for multiple nested attributes; thus the digit cannot be invoked without being wrong for the subsequent physicalinventarioitems being submitted... – Jerome Nov 25 '16 at 10:30