0

I am making a signup form and wanted to use jquery-validation plugin to check that user_name is unique.

The routes:

resources :users, :only => [:show] do
  collection do                      
    post 'check_user_name_uniq'     
    get 'check_email'                
    get 'check_password'             
  end  

controller:

def check_user_name_uniq
  render :json => User.valid_attribute?(:user_name, params[:user][:user_name]).to_json
end

javascript:

$("#new_user").validate({
  debug: true,
  rules: {
    "user[user_name]": {
      required: true,           
      remote: {
        url:  "/users/check_user_name_uniq", // check user_name uniqueness
        type: "POST",
        dataType: "json"
      }
    }                                        
  },...

And i set the X-CSRF-Token header by:

$.ajaxSetup({
  beforeSend: function(jqXHR) {
    jqXHR.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  }
});

But when i enter a user_name, there was still 401 error:

Started POST "/users/check_user_name_uniq" for 192.168.157.1 at 2013-04-26 23:52:22 +0800
Processing by UsersController#check_user_name_uniq as JSON
  Parameters: {"user"=>{"user_name"=>"tomwang"}}
Completed 401 Unauthorized in 36ms

I don't know why this error happened, because they said that the header could solve it: WARNING: Can't verify CSRF token authenticity rails

4

1 回答 1

0

您是否确保它<%= csrf_meta_tags %>存在于您的布局中?

于 2013-06-20T20:35:02.853 回答