2

I have a form with a lots of these text inputs:

<%= text_field_tag 'name[seq]['+dat.id.to_s+']', dat.seq%>

After send this form I want to save them to database, I try to get the values from inputs in each loop:

unless params[:name].nil?
  params[:name][:seq].each_with_index do |sq, i|
    puts sq
  end
end

But the output in terminal is wrong, for example if I have an input with the values

<%= text_field_tag 'name[seq][25]', 3%>

So I am going to expect the output is 3, but I will get to terminal this:

25
3

Is here something important, what I don't see?

1 Answer 1

1

Yes, you are missing something. Within your each_with_index block, sq will be an array and that's why you get that output.

So, what's going on here? Well, your params will contain this:

"name" => { "seq" => { "25" => "3" } }

And that means that params[:name][:seq] is this:

{ "25" => "3" }

Then you apply each_with_index to that to iterate through the Hash. If you do it like this:

params[:name][:seq].each_with_index do |(k,v), i|
  puts "-#{k}-#{v}-"
end

you'll see what's going on.

If you just want the 3 then you can iterate over params[:name][:seq] as above and just look at v inside the block or, if you know what the '25' is some other way, you could just go straight there:

three = params[:name][:seq]['25']
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so that mean... the index i is here totally useless, right?
@user984621: Pretty much useless, just an each would probably do you just as well.

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.