在使用Ajax保存之前,如何检查用户是否存在?

时间:2022-03-11 07:15:59

I have the following form:

我有以下表格:

<h1>New User</h1>
<%= form_for :user, url: users_path do |f| %>
  <p>
    <%= f.label :username %><br>
    <%= f.text_field :username %>
  </p>

  <p>
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

I would like to check to see if the user name exists before saving it.

我想在保存之前检查用户名是否存在。

I have never worked with Ajax, so an example to learn how can I do this would help.

我从未使用过Ajax,所以学习如何做到这一点的例子会有所帮助。

This is my controller:

这是我的控制器:

class UsersController < ApplicationController
  def new
  end

  def create
    #       render text: params[:user].inspect
    @user = User.new(user_params)
    @user.save
    redirect_to @user
  end

  def show
    @user = User.find(params[:id])
  end

  def index
    @users = User.all
  end

  private
  def user_params
    params.require(:user).permit(:username, :description)
  end
end

UPDATE

UPDATE

I'm trying this on my js file:

我在我的js文件上尝试这个:

$( document ).ready(function() {
    $('#user_username').blur(function() { 
        var value = $( this ).val();
        var url = "/users/" + value;        // your url of the function which will return a json or string containing result
    var data = {"username" : value}; // user name to send to server, so that you can compare this in the DB.
    var dataType = "json"; // it depends on the type you sent from the controller. it can be string, json etc..

    $.ajax({
      type: "POST",
      url: url,
      data: data,
      success: function(response){
        alert("pepitonas");
      },
      dataType: dataType
    }); 
    });
});

but the application dies. What I'm doing wrong.

但应用程序死了。我做错了什么。

Thanks

谢谢

2 个解决方案

#1


0  

You can do it with the help of an Ajax request. Include the jQuery script before using this code:

您可以在Ajax请求的帮助下完成此操作。在使用此代码之前包括jQuery脚本:

<script type="text/javascript">
  // foo is the id of your form
  $("#foo").submit(function(event){
    var url = ""; // your url of the function which will return a json or string containing result
    var data = {"user_name" : user_name}; // user name to send to server, so that you can compare this in the DB.
    var dataType = "json"; // it depends on the type you sent from the controller. it can be string, json etc..

    $.ajax({
      type: "POST",
      url: url,
      data: data,
      success: function(response){
        // here the code will come to handle response that you sent from your controller function
        // you can return from a string or json from server and then can decode your json right here.
      },
      dataType: dataType
    });    
  });

</script>

Hope this will help you.

希望这会帮助你。

#2


0  

I am not entirely sure why you need Ajax for this? All you need is to add validation on your user model:

我不完全确定为什么你需要Ajax呢?您只需要在用户模型上添加验证:

class User < ActiveRecord::Base

  validates :username, uniqueness: true

 end

This will reject the user when saving if the username exists.

如果用户名存在,这将在保存时拒绝用户。

In your controller change your create action:

在您的控制器中更改您的创建操作:

def create
  @user = User.new(user_params)
  if @user.save
    redirect_to @user
  else
    render :new
  end
end

And add some way to display an error in your view:

并添加一些方法在视图中显示错误:

  <% if f.object.errors.any? %>
    <p class='error'>
      Cannot save object due to following errors:
      <ul>
        <% f.object.errors.full_messages.each do |error|%>
          <li><%= error %></li> 
        <% end %>
      </ul>
    </p>
  <% end %>
  <p>
    <%= f.label :username %><br>
    <%= f.text_field :username %>
  </p>

#1


0  

You can do it with the help of an Ajax request. Include the jQuery script before using this code:

您可以在Ajax请求的帮助下完成此操作。在使用此代码之前包括jQuery脚本:

<script type="text/javascript">
  // foo is the id of your form
  $("#foo").submit(function(event){
    var url = ""; // your url of the function which will return a json or string containing result
    var data = {"user_name" : user_name}; // user name to send to server, so that you can compare this in the DB.
    var dataType = "json"; // it depends on the type you sent from the controller. it can be string, json etc..

    $.ajax({
      type: "POST",
      url: url,
      data: data,
      success: function(response){
        // here the code will come to handle response that you sent from your controller function
        // you can return from a string or json from server and then can decode your json right here.
      },
      dataType: dataType
    });    
  });

</script>

Hope this will help you.

希望这会帮助你。

#2


0  

I am not entirely sure why you need Ajax for this? All you need is to add validation on your user model:

我不完全确定为什么你需要Ajax呢?您只需要在用户模型上添加验证:

class User < ActiveRecord::Base

  validates :username, uniqueness: true

 end

This will reject the user when saving if the username exists.

如果用户名存在,这将在保存时拒绝用户。

In your controller change your create action:

在您的控制器中更改您的创建操作:

def create
  @user = User.new(user_params)
  if @user.save
    redirect_to @user
  else
    render :new
  end
end

And add some way to display an error in your view:

并添加一些方法在视图中显示错误:

  <% if f.object.errors.any? %>
    <p class='error'>
      Cannot save object due to following errors:
      <ul>
        <% f.object.errors.full_messages.each do |error|%>
          <li><%= error %></li> 
        <% end %>
      </ul>
    </p>
  <% end %>
  <p>
    <%= f.label :username %><br>
    <%= f.text_field :username %>
  </p>