你可以使用一些JavaScript(這個用jQuery寫的)對AJAX cheking:
$(function() {
$('[data-validate]').blur(function() {
$this = $(this);
$.get($this.data('validate'), {
user: $this.val()
}).success(function() {
$this.removeClass('field_with_errors');
}).error(function() {
$this.addClass('field_with_errors');
});
});
});
這個JavaScript將尋找屬性data-validate
任何領域。然後它將調用onBlur
事件處理程序(焦點在JavaScript世界中丟失)。模糊處理器將發送AJAX請求到data-validate
屬性中指定的URL,並通過參數user
輸入值。
下一頁修改您的觀點與驗證URL添加屬性data-validate
:
<%= text_field_tag(:user, :'data-validate' => '/users/checkname') %>
下一頁添加路線:
resources :users do
collection do
get 'checkname'
end
end
而最後一步創建您的驗證:
class UsersController < ApplicationController
def checkname
if User.where('user = ?', params[:user]).count == 0
render :nothing => true, :status => 200
else
render :nothing => true, :status => 409
end
return
end
#... other controller stuff
end
沒有Ruby的AJAX請求,你怎麼會知道用戶名是否在數據庫? – rubyprince 2011-04-28 08:42:00