Forum: Ruby on Rails How to use variables inside rhtml??

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8c70506408fddb9740b4de7339055c77?d=identicon&s=25 Prashant Tiwari (tiwaripk)
on 2006-03-10 11:27
Hi,

I want to use counters in my rhtml page for dynamic naming of my form
elements.
eg:- for 1st textbox name will be "text1"
     for 2nd textbox name will be "text2"
     ....& so on........

But here I want use a counter variable in rHtml file so that I will use
for loop for looping througn each set of elements in form & give name to
form elements as
"element_name"+i     (i is counter variable)
I tried it with following code but its nt working:-
===========
<%
@i=0
%>
<% for product in @products %>
<%= text_field 'product_item','product_id+@i.to_s',
:value=>product.id%></td>
<%end%>
============

But its not working proper as I m accessing the value of each textbox in
controller class as folllows:-
=========
for product in @products
params[:product_item][:product_id+'i']
next
========

it gives me error like:-
"'+' is undefined"

How to deal with this??????

Thanx in advance for ur reply.

Prash
Daa859590270ab904aa3460357750397?d=identicon&s=25 Kevin Elhart (kelhart)
on 2006-03-10 13:39
Prashant Tiwari wrote:
> ===========
> <%
> @i=0
> %>
> <% for product in @products %>
> <%= text_field 'product_item','product_id+@i.to_s',
> :value=>product.id%></td>
> <%end%>
> ============
>

Rails has build in support for this.

Use something like:

<% @products.each do |@p| %>
    <%= text_field 'p[]', .... %>
<% end>

This will automatically enumerate your fields in your form.

In your controller using params[:p] you fetch you an array of the values
entered in all the 'p' fields.
This topic is locked and can not be replied to.