Unique login


#1

Hello,

I’ve created my user model which validates against the database for a
proper user/pass combination. I’ve set validation options to ensure
that
both a user and password are entered.

I would like to check via an ajax call whether or not the username is
taken. I haven’t been able to find a tutorial covering this topic. Do
any of you know of one?

Thanks,
David


#2

observe_field is your friend here. Alternatively try a search for “live
search” or something similar.

An example (Untested)

<%= text_field “user”, “name” %>

<%= observe_field “user_name”, :url => { :controller => ‘user’, :action
=>
‘check_user_name’ }, :update => ‘user_name_result’, :on => ‘changed’,
:complete => “new Effect.Show( ‘user_name_result’)” %>

Additionally you can use the link_to_remote options. eg :loading,
:complete
etc

Then in your controller you have a method

def check_user_name
@user = User.find_by_name( params[:user][:name] ) || User.new
if @user.new_record?
render :inline => “Div contents to indicate that the name is
available. This will go in the div” and return
else
render :inline => “Div contents to indicate that it’s taken”
end
end


#3

David <lists@…> writes:
[…]

I’ve created my user model which validates against the database for a
proper user/pass combination. I’ve set validation options to ensure that
both a user and password are entered.

I would like to check via an ajax call whether or not the username is
taken. I haven’t been able to find a tutorial covering this topic. Do
any of you know of one?
[…]

What about something like the following (not tested):

In your login view:

<%= text_field ‘user’, ‘username’, :onChange => remote_function(:update
=>
‘availability_confirmation’, :url => {:controller => ‘users’, :action =>
‘check_for_availability’}, :with => “‘username=’+this.value”) %>

And in your controller (ie. ‘users_controller.rb’):

def check_for_availability
if User.find_by_username(params[:username]).empty?
render :inline => ’ Oh yeah! Good choice dude!
else
return :inline => ’ Please, choose another username
end
end

Cheers,
Marco