The respond_to block in a create controller in my Rails app is not redirecting on a successful save... I'm sure this is a simple solution, but I am inexperienced with Rails and this is the first time that I am encountering this problem.
The form is set so that :remote => true, and the controller is as follows...
def create
#store = current_user.stores.new(store_params)
respond_to do |format|
if #store.save
format.html { redirect_to root_path }
else
format.html { flash[:alert] = "Save failed! #{#store.errors.full_messages.join(";")}"
render "new" }
format.js {}
end
end
end
And while I'm on the subject, the code from the else portion of the conditional doesn't run either, except for format.js {}, which does run the code in my create.js.erb file (an alert, for the time being).
I'm working with Rails 4.2.5. Can someone help me to understand why the redirect and the alert are not working? Thank you!
EDITING TO SHOW SOLUTION
Based on Rich's answer, here's the solution that I came up with:
Controller:
def create
#store = current_user.stores.new(store_params)
flash.now[:alert] = "Save failed! #{#store.errors.full_messages.join(";")}" unless #store.save
respond_to do |format|
format.js
end
if #store.save
flash[:notice] = "New store created"
end
end
create.js.erb
<% if flash.now[:alert] %>
$("#alert_holder").empty();
$("#alert_holder").append("<%= j flash.now[:alert] %>");
<% else %>
window.location.href = "<%= root_url %>";
<% end %>
Note that I needed to add quotes around the redirect url.
On form success, the page redirects to root. On failure, the error message flashes but the form is not refreshed - any answers the user has entered remain.
remote: true is an ajax request.
Ajax is javascript, and as such will invoke the format.js method:
def create
#store = current_user.stores.new store_params
respond_to do |format|
if #store.save
format.js
format.html { redirect_to root_path }
else
format.js
format.html { flash[:alert] = "Save failed! #{#store.errors.full_messages.join(";")}"
render "new" }
end
end
end
The format.js method will call the /app/views/[:controller]/[:action].js.erb file, which will fire any of the JS you have inside it.
If you don't want to have the js format handling the response, you'll have to do away with respond_to and just have what you'd like to return (redirect_to won't work).
Ajax
There are several stipulations you need to appreciate with this:
Ajax cannot "redirect" (on its own)
Ajax will be treated as JS in your Rails controller
You have to "hack" the flash to get it working through JS
If you don't have experience with Ajax, the simple explanation is that it's a "pseudo-request"; it sends an HTTP request without having to reload the browser.
The pattern for Ajax is simple: Ajax request > server > Ajax response
You cannot "redirect" via Ajax unless you parse the response with javascript. As the Ajax acronym (Asynchronous Javascript And XML) suggests, the response is expected to be XML (IE no functionality).
--
To answer your question, you'll need to use flash.now for the "flash" message, and handle the response with your .js.erb file:
def create
#store = current_user.stores.new store_params
flash.now[:alert] = "Save failed! #{#store.errors.full_messages.join(";")}" unless #store.save
respond_to do |format|
format.js
format.html
end
end
This will allow you to call...
#app/views/stores/create.js.erb
<% if flash.now[:alert] %> alert("<%=j flash.now[:alert] %>"); <% end %>
window.location.href = <%= root_url %>;
Ref
Your new code can be improved a little :
def create
#store = current_user.stores.new store_params
if #store.save
flash[:notice] = "New store created"
else
flash.now[:alert] = "Save failed! #{#store.errors.full_messages.join(";")}"
end
respond_to do |format|
format.js
end
end
If you wanted to DRY up your code even more, you'll want to look at the responders gem:
#app/controllers/stores_controller.rb
class StoresController < ApplicationController
respond_to :js, only: :create
def create
#store = ...
respond_with #store if #store.save
end
end
If you have remote: true in your form, the format that is detected by the controller will be format.js, which is not present in your successful #store.save section.
2 options:
Default to normal form submit (by removing remote: true)
Load another js.erb file by adding format.js just like in the else clause then do the error handling there via some javascript.
Related
I’m using Rails 4.2.3. I want to submit a form in a modal dialog, so I have set up my form like so
<%= form_for #my_object, :remote => true do |f| %>
but if the user submits the form successfully, I would like to reload the page that invoked the modal dialog with a notice of “Saved Successfully.” I can’t figure out what I need to put in my “format.js” to make this happen. This is what I have in my controller so far …
def create
#my_object = MyObject.new(my_object_params)
#current_user = User.find(session["user_id"])
#my_object.user = #current_user
respond_to do |format|
if #my_object.save
format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
format.js { render action: ‘../users/index’, notice: ‘Saved Successfully’, location: #my_object }
else
format.html { render action: "index" }
format.js { render json: #my_object.errors, status: :unprocessable_entity }
end
end
end
Right now, a successful submission results in a 500 error complaining about missing partials when I try and execute the above. Pretty sure what I have is wrong anyway.
You can do the following:
#app/controllers/redirect.rb
...
format.js { render js: "window.location='#{url.to_s}'" }
...
If you like keeping things separated, just put format.js in your controller and do the javascript redirect in your view (redirect.js.erb)
In both cases, just set flash[:notice] to whatever you need before redirecting.
redirect_to events_path, format: 'js'
For this you will need to have events/index.js.erb in your file structure.
If you are redirecting anyway, you might as well avoid the remote/AJAX call, and just redirect from the create action.
<%= form_for #my_object do |f| %>
and
def create
#my_object = MyObject.new(my_object_params)
...
redirect_to some_path
end
If you have want to redirect it after successfully create/updated and just use .html method. Otherwise just use JS option like in this LINK.
def create
#my_object = MyObject.new(my_object_params.merge(user: User.find(session["user_id"])))
respond_to do |format|
if #my_object.save
format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
else
....
end
end
end
That will help you, from your controller
render :js => "window.location = '/jobs/index'"
I am uploading several images (from http://localhost:3000/choices/new), which work fine, however, I am trying to redirect back to: http://localhost:3000/choices after it saves.
Here is my controller:
#app/controllers/choices_controller.rb
def create
#choice = Choice.new(choice_params)
#choice.filename = params[:filename].titleize
if #choice.save
respond_to do |format|
format.html { redirect_to choices_path }
format.json { head :no_content }
end
end
end
In Rails Console, it outputs:
Redirected to http://localhost:3000/choices
Completed 302 Found in 58ms (ActiveRecord: 52.8ms)
Yet, the "new" page remains static. Any idea on how to correctly redirect this, perhaps with a flash message saying "Images uploaded succesfully"?
Thanks very much!
I only just learnt what asynchronous requests are, so I hope this helps...
If you're sending a 'background' request with JS, how can the controller affect your browser's viewport?
The controller is server-side, and is loaded every time you send a request. This means that unless your actual browser made an HTTP request directly to the controller, how can it cause a change in the view you have already rendered?
JS is client-side technology, which means that it can cause things to happen on your behalf, but its scope is limited to taking "DOM" elements & interacting with them.
I looked at some pretty informative answers in this regard, and found these ideas:
Rails 3.2.0 - Redirecting after a JSON call is made
Rails 3: How to "redirect_to" in Ajax call?
https://www.ruby-forum.com/topic/206571
All of these answers say a similar thing: you need to handle the redirect with JS
Why not do something like this:
#app/controllers/choices_controller.rb
def create
#choice = Choice.new(choice_params)
#choice.filename = params[:filename].titleize
if #choice.save
respond_to do |format|
format.html { redirect_to choices_path }
format.json { render :json => {
:location => url_for(:controller => 'choices', :action => 'index'),
:flash => {:notice => "File Uploaded!"}
}
end
end
end
#assets/javascripts
$(document).ready(function() {
$.ajax({
success: function(data) {
window.location = data.location
}
})
});
A much cleaner way to do it will be to send a plain JS request, and have this:
#/views/new.js.erb
window.location = <%= choices_path %>
#app/controllers/choices_controller.rb
def create
#choice = Choice.new(choice_params)
#choice.filename = params[:filename].titleize
if #choice.save
respond_to do |format|
format.html { redirect_to choices_path }
format.js
end
end
end
This i similar to the above answer, but a little more versatile. It took some playing but I finally got it working, and I signed up for StackOverflow just so I could post an answer. Here is my solution (though I was using JS as my format)
respond_to do |format|
format.html { redirect_to choices_path }
#path = url_for(:controller => 'choices', :action => 'index')
- or - choices_path for a named route
format.js { render 'shared/redirect'}
:flash => {:notice => "File Uploaded!"}
end
Now in your shared/redirect.js.erb file (notice this is a shared file, so you can reuse it):
#shared/redirect.js.erb
window.location.href = '<%= #path %>';
I need to pass two instance variables to a javascript file that is being used by an ajax request to update a user display. This is what I need to do:
respond_to do |format|
if #post.save
format.js { #post #user_vote } # <-- right here
else
format.html { redirect_to :back, :alert => 'There was an error in removing the vote' }
end
end
How is this done?
There is no need to pass the instance variables if you use js.erb files. You can directly put the rails tag and access those variables inside the js.erb file
Eg:
In your controller just put
format.js #instead of format.js { #post #user_vote }
and in js.erb file you can access the instance variable as
$('#ele').html("<%= #post.name %>");
The instance variables in your ActionController action are available in your views automagically. E.g. your controller:
# posts_controller.rb
def update
# Your implementation here
#post = ...
#user_vote = ...
respond_to do |format|
if #post.save
format.js
format.html { redirect_to post_path(#post) }
else
format.js { ... }
format.html { redirect_to :back, ... }
end
end
end
Then in your update.js.erb:
# update.js.erb
console.log('Post: <%= #post.inspect %>');
console.log('User vote: <%= #user_vote %>');
# Your JS implementation here
(Also I noticed your logic in the respond_to block is probably going to cause problems. You should render both js and html formats for both success and failure conditions of #post.save.)
I am trying to get some Javascript working in my Rails app.
I want to have my index page allow me to edit individual items on the index page, and then reload the index page upon edit.
My index.html.erb page looks like:
<div id="index">
<%= render 'index' %>
</div>
In my index.js.erb I have:
$('#index').html("<%=j render 'index' %>");
and in my holders_controller:
def edit
holder = Holder.find(params[:id])
end
def update
#holder = Holder.find(params[:id])
if #holder.update_attributes(params[:holder])
format.html { redirect_to holders_path } #, flash[:success] = "holder updated")
## ^---Line 28 in error
format.js
else
render 'edit'
end
end
When I load the index page it is fine. As soon as click the edit button and it submits the form, I get the following:
But if I go back and refresh the index page, the edits are saved. What am I doing wrong?
You forgot to write responds_to block:
def update
#holder = Holder.find(params[:id])
if #holder.update_attributes(params[:holder])
respond_to do |format|
format.html { redirect_to holders_path } #, flash[:success] = "holder updated")
format.js
end
else
render 'edit'
end
end
But I am suspicious about your index.html.erb, I don't think that will really work the way you think.
I am trying to do an AJAX call with Rails. The call is to the change_profile action in my controller. The contents of this action are as follows:
def change_profile
#test = params[:test]
puts "AAAAAAA #{#test}"
respond_to do |format|
format.html
format.js
end
render(:text => "FINISHED THE AJAX REQUEST")
end
When I call this, however, the Rails console says:
ActionView::MissingTemplate (Missing template main/change_profile ....
I don't understand why this is happening. Since I'm rendering text, shouldn't it know not to try to find the template and just render the text?
When left without a {}, the respond_to block looks for a file called change_profile.erb.js or some other change_profile.xxx.js. Add your code within the respond_to block
def change_profile
#test = params[:test]
puts "AAAAAAA #{#test}"
respond_to do |format|
format.html
format.js {
render :text => "FINISHED THE AJAX REQUEST"
}
end
end