我正在尝试通过此gem将基于模型的客户端验证添加到我的联系表单中:client side validations 我在他们的页面上按照教程。我添加了gem,捆绑它,运行生成器,并复制资产。
不幸的是它不起作用。当我提交表单时,它不会验证。只需转到创建控制器并呈现有关错误的响应。
型号:
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :phone, :body
validates :name, :email, :phone, :body, :presence => true
validates :email, :format => { :with => %r{.+@.+\..+} }, :allow_blank => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
HTML:
<h2>Formularz kontaktowy</h2>
<%= form_for @message, :url => contact_path,
:html => {:class => "form-horizontal"},
:validate => true do |f| %>
<% if flash %>
<% flash.each do |key,value| %>
<%= content_tag(:div, value, class: "alert alert-#{key}") %>
<% end %>
<% end %>
<div class="control-group">
<%= f.text_field :name, :placeholder => "Imie Nazwisko / Nazwa firmy" %>
</div>
<div class="control-group">
<%= f.text_field :email, :placeholder => "Adres e-mail" %>
</div>
<div class="control-group">
<%= f.text_field :phone, :placeholder => "Telefon kontaktowy" %>
</div>
<div class="control-group">
<%= f.text_area :body, :placeholder => "Treść zapytania", :rows => 5 %>
</div>
<div class="control-group">
<%= f.submit "Wyślij", :class => "btn" %>
</div>
<% end %>
控制器:
class ContactsController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
NotificationsMailer.new_message(@message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end