我有这个表格,我试图将表格的内容提交给模特" Leeds"然后根据数据是否通过模型验证显示成功/失败消息。
我遇到的问题是当我点击"发送消息"按钮,它从Root
到Root/leeds
。
这是我使用的形式:
<%= form_for @leed, {url:root_path, html: {id:"contactForm", name:"sentMessage", novalidate:true}} do |leed| %>
<div class="row">
<div class="col-md-6">
<!-- Name -->
<div class="form-group">
<%= leed.text_field :name, class: "form-control", :placeholder => "Your name *", :required => true, :data => {:validation_required_message => 'Please enter your name.' } %>
<p class="help-block text-danger"></p>
</div>
<!-- Email -->
<div class="form-group">
<%= leed.email_field :email, class: "form-control", :placeholder => "Your email *", :required => true, :data => {:validation_required_message => 'Please enter your email address.' } %>
<p class="help-block text-danger"></p>
</div>
<!-- Phone -->
<div class="form-group">
<%= leed.telephone_field :phone, class: "form-control", :placeholder => "Your phone *", :required => true, :data => {:validation_required_message => 'Please enter your phone number.' } %>
<p class="help-block text-danger"></p>
</div>
</div>
<!-- Message -->
<div class="col-md-6">
<div class="form-group">
<%= leed.text_area :message, class: "form-control", :placeholder => "Your message *", :required => true, :data => {:validation_required_message => 'Please enter a message.' } %>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="clearfix"></div>
<!-- Submit -->
<div class="col-lg-12 text-center">
<div id="success">
<%= render 'shared/error_messages' %>
</div>
<%= button_tag "Send Message", class: "btn btn-xl" %>
</div>
</div>
<% end %>
这是我的routes.rb:
Rails.application.routes.draw do
root 'home#index'
post "/" => 'home#create'
end
这是我的HomeController方法:
def create
@leed = Leed.new(leed_params)
if @leed.save
#update page to reflect success
flash[:success] = "Thank you, we'll contact you as soon as possible"
else
#update page to flect failure
flash[:danger] = "There was an issue with the login attempt #{@leed.errors.full_messages.inspect}"
end
# redirect_to thank_you.html.erb
render nothing:true
end
答案 0 :(得分:0)
在#create方法的最后,您有render nothing: true
。这意味着帖子请求将被提交给/ lead,但是服务器不会告诉浏览器去其他地方,所以浏览器将保留在/ lead url。如果您希望在完成发布请求后将浏览器重定向到其他页面,则可以在创建操作结束时添加重定向。希望有所帮助!
答案 1 :(得分:0)
Puhlze是对的,您应该能够将页面重定向到Flash消息应该显示的位置。您还可以创建remote: true
表单并创建一个create.js.erb
文件,该文件将弹出通知消息而无需重新呈现页面;这是我们在使用AJAX提交时通常会做的事情。