I've created a basic username / password generator which creates X random usernames and passwords. I used this post as the basis. It works ok in the console but I do not understand how to get it to work properly in my RoR3.1 application.
I need to create a simple form which I can input the following variables:
- Number of iterations (X) required
- Length of username (Y)
- Length of password (Z)
Then, when I click save, I need the application to create X usernames and password and save to the db.
I have managed to get it working by calling the action upon page load, but I do not know how to create a form which will pass over the variables.
I've created this in my user model:
class User < ActiveRecord::Base
private
def self.generate_batch
10.times do
username = ""
password =""
5.times { username << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
5.times { password << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
User.create!(:username => username, :check_attributes => [ {:attribute_name => "User-Password", :value => password, :op => ":="}])
end
end
end
In my users controller, I created a new action:
def new_batch
@user = User.new
respond_to do |format|
if @user.save
@user = User.generate_batch
else
format.html { render action: "new_batch" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
And in my routes:
get "/batch" => "users#new_batch"
I started with a blank form to see if I could at least get it going with the variables hardcoded:
= simple_form_for @user do |f|
= f.submit
When I hit submit, it looks like it tries to use my create action, instead of generating the batch...
What do I need to do to:
- Get the form to submit properly
- Enter the variables as above
Thanks in advance
-- UPDATE --
Following the advice below, I've created two controllers:
routes.rb now has this:
get "/batch" => 'users#new_batch'
put "/batch" => 'users#new_batch_create'
And the controller like this:
def new_batch
end
def new_batch_create
@user = User.generate_batch
end
Now, when I hit submit, it processes through loop :)
Still don't quite understand how to pass the variables over from the form...