flash[:notice] not working when using AJAX in Rails - ruby-on-rails

I've tried different variants of make flash[:notice] working without reload.
Stackoverflow gave me this - How do you handle Rail's flash with Ajax requests?, but I can't find solution, that worked for me.
For example, added to my controller:
def create
#entry = Entry.new(params[:entry])
respond_to do |format|
if #entry.save
format.html { redirect_to #entry, notice: 'Entry was successfully created.' }
format.js {
flash.now[:notice] = 'Website was successfully created.'
render action: 'create'
}
else
format.html { render action: "new" }
format.js { render action: "new" }
end
end
end
create.js
$('<%= j render #website %>').appendTo('#websites').hide().fadeIn();
$(".alert").html("<%= escape_javascript(flash[:notice]) %>"); $(".alert").show(300);
$("#new_website")[0].reset();
but it didn't work.
Can someone tell me understandable full solution, that worked for him ?

Do you make a typo on your js template filename? it should be create.js.erb but not create.js
and please strictly follow the https://stackoverflow.com/a/8873592/557863 , then make your changes on it.

You're submitting new entries via Ajax, so you shouldn't use the flash -- it's intended for redirect responses, but you're not redirecting. To indicate success or failure, you'd need to write that into your JavaScript response.

Related

Custom actions and redirecting properly after success on submit

I'm actually working on a small app, where a user can create an event. It has to be done in three steps.
To achieve this, I created two custom actions in the related controller. Each view has a form using the update url.
Then I customized the update method this way:
def training
#event = Event.find(params[:event_id])
#coach = Coach.find(#event.coach_id)
end
def confirm
#event = Event.find(params[:event_id])
end
def update
respond_to do |format|
if #event.update(event_params)
if params[:commit] == 'next'
format.html { redirect_to booking_event_confirm_path(#event), notice: 'Event was successfully updated.' }
else
format.html { redirect_to booking_event_path(#event), notice: 'Event was successfully updated.' }
end
else
if params[:commit] == 'next
format.html { render :training }
else
format.html { render :edit }
end
end
end
end
As a Rails beginner, I would be happy to get some feedback... Does this seems ok, or would it be a better way to achieve my goal?
Thx in advance!
Your solution is not bad, but there is a better way to achieve it. I would suggest you checking Wicked gem and this tutorial.
In general, google a wizard or multi-step form.

Getting status: code on ajax response in a .js.erb file on Rails

I've just started to play with Rails applications and I'm trying to use Ajax on a form, but I don't know how to catch the status code inside a js.erb file. I'm following this tutorial: http://guides.rubyonrails.org/working_with_javascript_in_rails.html
On my Users controller I have a code for my update method:
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.js {}
format.json { render json: #user, status: :created, location: #user}
else
format.html { render action: 'edit' }
format.js {}
format.json { render json: #user, status: :unprocessable_entity }
logger.debug #user.response_errors
end
end
I've created a update.js.erb file inside my views/users/ folder and is very easy to debug the #user var, but I don't know how to get the status code setted on my method.
Sorry if it's a stupid question, but I'm new with rails and I'm trying to follow all the frameworks concepts to the letter and I don't know the best pratices to create responses to Ajax requests.
What I'm trying to achieve is something like this:
#on my update.js.erb
if( status == 'created' ) {
alert( 'Ok, created' )
} else {
alert( 'Something wrong happened' )
}
I appreciate any help.
Option 1: Check Validity Inside update.js.erb
This is the option that I recommend in most cases.
update.js.erb is an ERB template whose result is a JavaScript code to evaluate on the client. In this case, you can make it look like:
<% if #user.valid? %>
alert('Ok, created');
<% else %>
alert('Something wrong happened');
<% end %>
The decision which alert to displays happens server-side. The client receives either:
alert('Ok, create');
or
alert('Something wrong happened');
depending on the status of #user.
Option 2: Two separate js.erb files
You can split your update.js.erb into two files. update.js.erb should contain the happy path code:
alert('Ok, create');
update-error.js.erb should contain some error handling:
alert('Something wrong happened');
Then you decide which one to display in your controller:
respond_to do |format|
if #user.save
# ...
format.js {}
# ...
else
# ...
format.js { render 'update-error' }
# ...
end
end
I would try to do:
format.js {render json: {#user, status: :created, location: #user}}

Rails session store stopped working correctly

I have a Rails 3.2 app that uses session store in the controllers to get the user back to the screen they were previously on.
It's been working fine for over a year. All of a sudden, the production version on Heroku, has started having issues. The user is looking at a worequest and clicks on the following in order to add a comment.
<%= link_to 'New Comment', new_comment_path(:worequest_id => #worequest.id), :class => 'btn btn-primary' %>
This is the code I use:
def new
#comment = Comment.new
#comment.build_attachment
#worequest = params[:worequest_id]
session[:return_to] ||= request.referer
respond_to do |format|
format.html # new.html.erb
format.json { render json: #comment }
end
end
# POST /comments
# POST /comments.json
def create
#comment = Comment.new(params[:comment])
respond_to do |format|
if #comment.save
if session[:return_to] != nil
format.html { redirect_to session.delete(:return_to), notice: 'Comment was successfully created.' }
format.json { render json: #comment, comment: :created, location: #comment }
else
format.html { redirect_to :back, notice: 'Comment was successfully created.' }
format.json { render json: #comment, comment: :created, location: #comment }
end
else
format.html { render action: "new" }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
In development and staging (on Heroku), the user goes back to the worequest after entering a new comment.
Now in Production, the url looks like this:
mywebsite/comments instead of mywebsite/worequests/639
I'm not even sure where the session[:return_to] gets stored. Therefore, I'm having trouble debugging the issue.
Thanks for your help!!
Are you able to replicate this behavior 100% of the time, or just seeing it sometimes in your log?
It looks like someone is getting to comments#new from /comments (comments#index). Is there a route to /comments?
Run rake routes to see all your routes.
If there is a route to comments#index, and there's no reason for it to be exposed because you only intend for people to post comments from within the context of a specific article, consider removing it the comments#index route.
Also, one thing to consider, request.referrer is not always available. It's sent by the client who may choose not to send it (e.g. certain privacy extensions remove this header).

jQuery selector for rails render file

I'm Implementing Ajax with Rails by adding a new post in runtime without refreshing the page.
The problem is I want to render a specific view by this script which is allocated in create.js.erb
$('<%=render(:file => "posts/post.html.erb)%>').insertBefore($('.posts').children('div.post-box').first());
But it doesn't work, Can anyone tell me what's wrong on this script and how to select html code in jquery from a specific view?
and this's the create action
def create
#post = Post.new(params[:post])
respond_to do |format|
if #post.save
format.html { redirect_to :back, notice: 'Post was successfully created.' }
format.js
end
end
All you need is add escape_javascript method, just like this
$('<%= escape_javascript(render(:file => "posts/post.html.erb"))%>').insertBefore($('.posts').children('div.post-box').first());

Conditional redirect after update

I would like to do a conditional update in ruby on rails 3.1
Where based on the location you came from, after update, an redirect will be done.
Splitted my 1 big form in to separate smaller ones, so now the Idea is to redirect to the correct subform.
For example the form can be submitted from:
profile basics form
Profile details form
The only thing I could come up with is checking the action name and use that to redirect. But its very ugly and long code and not fully working either. What would be the railsway of doing this?
This is my controller update action:
def update
#profile = Profile.find(params[:id])
respond_to do |format|
if #profile.update_attributes(params[:profile])
format.html { redirect_to #profile, notice: 'Profile was successfully updated.' }
else
format.html {
render :action => "edit_basics"
#
}
end
end
end
Why not just pass the redirect location as a hidden_field in the form, then have each form set it as needed:
redirect_to params[:redirect_location]
You could also do this using steps or something if you don't want to expose the raw string in your HTML:
redirect_to location_for_step(params[:step])

Resources