我有一个表单,当用户提交并且用户未登录时,他们会收到登录的模式提示。用户登录后,模式将消失,但他们必须再次单击表单上的提交按钮。如果在成功登录后,模式消失并且表单自动提交,那就太好了。
所以在sessions/create.js.erb
里面我添加了以下内容。
# create.js.erb
<% if signed_in? %>
$('#ajax-modal').modal('hide').empty();
$('#new_response).submit();
<% else %>
$('#ajax-modal').html('<%= j render("sessions/form") %>').modal();
<% end %>
这有效,但不可缩放。首先,我可能有其他形式 - 不仅仅是#new_response
- 需要类似的行为。因此,每次添加新表单时,我都必须编辑create.js.erb
并添加if (form exists) submit();
。在其他时候,模式用于登录,但根本不涉及任何表单。
有没有办法附加一个钩子来告诉sessions/create.js.erb
仅在存在表单时才提交表单,但对表单 ID 一无所知?基本上,它通过了。
# responses/_form.html.slim
= form_for [@discussion, @response], remote: true do |f|
= f.label :content, "Comments"
= f.text_area :content, rows: 8
= f.submit "Reply", class: 'btn btn-success reply', 'data-disable-with' => "Reply"
# Responses controller
class ResponsesController < ApplicationController
before_filter :require_authentication, except: :index
...
def require_authentication
redirect_to signin_path unless signed_in?
end
end
您可以使用某种方式来跟踪触发提交的表单,例如
# ResponsesController
class ResponsesController < ApplicationController
before_filter :require_authentication, except: :index
def require_authentication
session[:form_track_code] = params[:form_track_code] if [:put, :post].include?(request.method_symbol) && params[:form_track_code].present?
redirect_to signin_path unless signed_in?
end
end
# SessionsController
class SessionsController < ApplicationController # or devise?
def create
@form_track_code = session.delete[:form_track_code]
super # or whatever you implemented
end
end
# create.js.erb
<% if signed_in? %>
$('#ajax-modal').modal('hide').empty();
<% if @form_track_code.present? %>
$('input[type=hidden][value="<%= @form_track_code %>"]').parents('form').submit();
<% end %>
<% else %>
$('#ajax-modal').html('<%= j render("sessions/form") %>').modal();
<% end %>
# application.js
$('form[data-remote=true]').each(function() { $(this).append('<input type="hidden" name="form_track_code" value="' + Math.random() + '" />'); });