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.

0

2 Answers 2

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}}}}`
Sign up to request clarification or add additional context in comments.

3 Comments

@Jerome, please check this answer for multiple nested attributes.
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 Integererror. params[:physicalinventario][:physicalinventarioitems_attributes].each do |key, value| will process properly.
I used to_f there.
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

1 Comment

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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.