我有以下表格:
<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 %>
我想在保存之前检查用户名是否存在。
我从未使用过Ajax,所以学习如何做到这一点的例子会有所帮助。
这是我的控制者:
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
更新
我在我的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
});
});
});
但是应用程序死了。我做错了什么。
由于
答案 0 :(得分:0)
您可以在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>
希望这会对你有所帮助。
答案 1 :(得分:0)
我不完全确定为什么你需要Ajax?您只需要在用户模型上添加验证:
class User < ActiveRecord::Base
validates :username, uniqueness: true
end
如果用户名存在,这将在保存时拒绝用户。
在您的控制器中更改您的创建操作:
def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render :new
end
end
并添加一些方法在视图中显示错误:
<% 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>