我在Rails上建立了一个红宝石注册页面。我想验证此注册表单。例如-如果用户将任何部分留空,则表单将显示错误消息。它还将检查给定的电子邮件是否唯一。如何通过不更改表单来做到这一点?
#This my logins_controller.rb file
class LoginsController < ApplicationController
skip_before_action :verify_authenticity_token
def index
@subscriber=Subscriber.new()
end
def sign_up
subscriberNew = Subscriber.new
subscriberNew.name = params[:name]
subscriberNew.cus_user_name = params[:user_name]
subscriberNew.cus_password = params[:password]
subscriberNew.cus_email = params[:email]
result = subscriberNew.save
respond_to do |format|
msg = { :status => "ok", :message => "Success!" }
format.json { render :json => msg }
end
end
def validate_signup
#what should i write here?
end
end
这是我的注册表格
<div class="container">
<div class="shadow-lg p-3 mb-5 bg-white rounded view-card">
<h4 class="card-title">
<a href="/product_types">
<i class="material-icons">
arrow_back_ios
</i></a></h4>
<form id="signup_form" method="post" action="/sign-up">
<p class="h4 mb-4">Register to Binimoy</p>
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control mb-4" placeholder="Name">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control mb-4" placeholder="Email">
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" class="form-control mb-4" placeholder="Phone">
<label for="name">Password</label>
<input type="password" name="password" id="password" class="form-control mb-4" placeholder="Password">
<div class="form-row mb-4">
<div class="col">
<button class="btn btn-default my-4 btn-block" type="reset">Reset</button>
</div>
<div class="col">
<button type="button" class="btn btn-info my-4 btn-block" id="submitAnchor">Submit</button>
</div>
</div>
</form>
</div>
答案 0 :(得分:1)
首先,在您的视图中使用Rails帮助器并按照here中的说明编写表单。
<%= form_with url: sign_up_path do |form| %>
<%= form.label :email %>
<%= form.text_field :email %>
...
<%= form.submit %>
<% end %>
第二,按照here所述在订户模型中使用验证。
validates :email, presence: true, uniqueness: true
...
希望它会有所帮助;)
答案 1 :(得分:1)
Rails是一个对如何做事有强烈见解的框架。您正在做的事情不是Rails方式,这会使事情变得更复杂。
如果您真的不想更改表格(强烈建议)
添加验证,检查save
的返回值并发送回一些错误消息
在您的模型中:
validates :email, presence: true, uniqueness: true
在您的控制器中:
if subscriber.save
render json: {status: "ok", message: "success"}
else
render json: {status: "nok", message: "something went wrong"}
end
可能您应该放弃status
属性,并为此使用HTTP状态代码(发送回201(已创建)和422(不可处理的实体)响应)
一些其他建议,以使您的代码更具可读性:
使用Ruby命名约定:
subscriberNew
应该是
subscriber_new
因为Ruby使用camel_case
但实际上不需要new
后缀,所以subscriber
就足够了
cus_username
,...),并且在不需要时不添加前缀