我想在注册过程中首先进行表单验证,我想检查user_name
之前是否使用过,并且我想在不使用gems的情况下从头开始,以便了解如何操作它有效,所以我找到了这个 question我正在尝试实现我在那里找到的答案
1-我使用js2coffee将js代码更改为coffe为了在 users.js.coffee 中而不是在 application.js 中使用它
jQuery ->
$("[data-validate]").blur ->
$this = $(this)
$.get($this.data("validate"),
user: $this.val()
).success(->
$this.removeClass "field_with_errors"
).error ->
$this.addClass "field_with_errors"
2-我的路由文件中有这个
devise_for :users, :controllers => { :registrations => "users" }
resources :users, only: [:index, :new, :create, :show, :destroy, :edit, :update] do |user|
collection do
get 'checkname'
end
end
3-在我的 users_controller 内部
def checkname
if User.where('user_name = ?', params[:user]).count == 0
render :nothing => true, :status => 200
else
render :nothing => true, :status => 409
end
return
end
4-我的表单new.html.erb
<%= simple_form_for(@user) do |f| %>
<%= f.error_notification %>
<div class="inputs">
<%= f.input :user_name, input_html: { data-validate="/users/checkname" }%>
</div>
<div class="actions">
<%= f.button :submit, "Accept", :class => "btn btn-inverse" %>
</div>
<% end %>
我收到的错误(因为如果我删除 input_html: { data-validate="/users/checkname"}
,我不知道如何使 data-validate 属性起作用,错误是消失了,但我无法进行用户名验证)
SyntaxError at /users/new
syntax error, unexpected '}', expecting tASSOC
任何帮助,因为我已经搜索了很多,但找不到更新的示例
最佳答案
我实在找不到任何理由不使用 uniqueness validator :
class User < ActiveRecord::Base
validates :user_name, uniqueness: true
end
另外,不要使用 js2coffee - 你会得到糟糕的代码,而且你永远不会以这种方式学习如何使用 js 或 Coffeescript。
关于“您不能在一天的同一时间发布两个事件” - 您可以通过内置验证来做到这一点:
validates :event, :uniqueness => {:scope => [:day]}
关于javascript - 注册时检查用户名唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19450561/