Reputation: 1017
I have a rails app where I have a form in a popup window. I want the window to close after the user hits submit.
In my application.js, I have
function windowClose() {
"setTimeout(windowClose(), 15000);";
}
My form is
<%= form_tag(controller: 'bedsheet_lines', action: 'bedsheet_line_comments', method: "get", id: '3081') do %>
<%=text_area_tag e_comment, @current_bedsheet_line.comments %></td>
<%= submit_tag "submit", :onclick => "setTimeout(windowClose(), 5000);"%>
<% end %>
My route is
get '/bedsheet_liner/comments' =>'bedsheet_lines#bedsheet_line_comments', as: 'bedsheet_line_comments'
post '/bedsheet_liner/comments' => 'bedsheet_lines#bedsheet_line_comments'
My controller is
def bedsheet_line_comments
@bedsheet_line = BedsheetLine.find(3081)
render :layout => 'alternate'
if params[:comments].present?
@bedsheet_line = @bedsheet_line.update_attributes(:comments => params[:comments])
end
# redirect_to bedsheet_line_path(@bedsheet_line.id)
end
I need to call render :layout => 'alternate'
so that the popup does not have the header, footer or nav that application.html.erb provides.
If I try to call the redirect_to bedsheet_line_path(@bedsheet_line.id)
that is commented out, I get
AbstractController::DoubleRenderError in BedsheetLinesController#bedsheet_line_comments
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
I tried working around this by using Javascript ( <%= submit_tag "submit", :onclick => "setTimeout(windowClose(), 5000);"%>
) to close the window after a submit but while that closes the window, it prevents to update from being written. The delay was an attempt to try to allow Rails to finish writing the data before closing the window.
Summary - I want to be able to render an alternate layout AND redirect the user after they hit the submit button.
Upvotes: 1
Views: 265
Reputation: 694
Firstly, you should separate your get and post actions.
Let us say the get request is served by show_bedsheet_line_comments
action:
def show_bedsheet_line_comments
@bedsheet_line = BedsheetLine.find(3081) # I don't know if this is used in your view
render :layout => 'alternate'
end
and your post request is served by bedsheet_line_comments
action:
def bedsheet_line_comments
@bedsheet_line = BedsheetLine.find(3081)
if params[:comments].present?
@bedsheet_line = @bedsheet_line.update_attributes(:comments => params[:comments])
end
render js: "setTimeout(windowClose(), 5000);"
end
Upvotes: 1