Rails 3.2 create a form that's used in the footer of every page

瘦欲@ 提交于 2019-12-01 14:03:58

change your form to this

<%= form_for MailingList.new, html: { remote: true } do |f| %>

so you don't have to worry about instance variables. You should also pass remote: true so the form is submitted via ajax. To show error, create a file called create.js.erb under app/views/mailing_lists and add the following (just a simple script that appends the errors before the form)

$('.error-messages').remove();
<% if @mailist_list.errors.any? %>
  $('#new_mailing_list').before('<ul class="error-messages"></ul>');
  <%= @mailing_list.errors.full_messages.each do |msg| %>
    $('.error-messages').append('<li><%= escape_javascript msg %></li>');  
  <% end %>
<% end %>

You can change your form_for method to this:

<%= form_for :mailing_list, url: mailing_lists_path do |f| %>

Then you no longer need to initialize @mailing_list for every page.

The caveat is that you cannot render the errors in the footer. You would need to create a new.html.erb view using the code in the question, that can be rendered if there are any errors when saving in the create action.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!