Saving a new object n times to the DB

Hello,

I have a generate method that generate PIN codes and serial numbers n
times,
n comes from a user-submitted form, something like that:

<% form_for :card, :url => {:action => “generate”} do |f| -%>

Number of cards
<%= f.text_field :number_of_cards, :size => 10 %>

<%= submit_tag ‘Generate’ %>
<% end -%>

In the controller I have:

def generate
params[:number_of_cards].to_i.times do
pin = rand(999999999999).to_s.center(12, rand(9).to_s)
serial = rand(999999999999).to_s.center(12, rand(9).to_s)
Card.create({:pin => pin, :serial => serial})
end
end

Everything looks OK, but when I put a number and submit the form I got
nothing! No error messages and no records are saved to the database !!!
When I for example put :
3.times do
… etc

3 new records are successfully created in the database !

what’s the problem? Maybe params[:number_of_cards] doesn’t get the value
from the form? Why? And if so why don’t I get error about some nil
value?

Your help is really appreciated.

Regards

On 19 Mar 2008, at 18:44, [email protected] wrote:

3 new records are successfully created in the database !

what’s the problem? Maybe params[:number_of_cards] doesn’t get the
value from the form? Why? And if so why don’t I get error about some
nil value?

Because the parameter is being submitted as params[:card]
[:number_of_cards] (that’s what form_for does). You can see this in
your logs. You get no error because nil.to_i is 0

Fred

On Mar 19, 2008, at 2:44 PM, [email protected] wrote:

<% end -%>

value from the form? Why? And if so why don’t I get error about some
nil value?

Your help is really appreciated.

Regards

You have form_for :card and then f.text_field :number_of_cards, so
you’ll get a params[:card][:number_of_cards]

Your params[:number_of_cards] is therefore almost certainly nil and
nil.to_i == 0

It can help tremendously to put:
<%= debug(params) %>

Into the view that comes back so you can see what really happens (or
just go look in the log/development.log where you should also see the
params hash).

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

Thanks Frederick and Rob, now it works :slight_smile:
This debug option is really useful I didn’t know about it before>

Thanks

On 19/03/2008, Rob B. [email protected] wrote:

%>


Card.create({:pin => pin, :serial => serial})

-Rob

Rob B. http://agileconsultingllc.com
[email protected]


Anas Marrawi
Visit me at: www.anasonline.net

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs