Rails 3. the "flash" doesn't work on some pages - ruby-on-rails

I'm using the "web_app_theme" gem. The problem is that the flash error and warning messages don't work.
For example, in the Sign In page it does work; but in the Forgot Password page it doesn't work. I tested it by displaying the contents of the flash <%= debug flash %>.
This is what I get in the Sign In page...
!ruby/object:ActionDispatch::Flash::FlashHash
used: !ruby/object:Set
hash:
:alert: true
closed: false
flashes:
:alert: Invalid email or password.
now: !ruby/object:ActionDispatch::Flash::FlashNow
But in the Forgot Password page I get...
!ruby/object:ActionDispatch::Flash::FlashHash
used: !ruby/object:Set
hash: {}
closed: false
flashes: {}
now: !ruby/object:ActionDispatch::Flash::FlashNow
I'm thinking that it might be related to not using haml. In the Sign In page I'm using haml but in the Forgot Password page I'm using erb. I'm confused because the contents of 'flash' should be the same regardless of the format, right?

This has little to with the view code you use.
From your question, it's clear that the flash in the Forgot Password page has not been set.
Either that or it has been set and erased. Using HAML or ERB is not relevant since the Rails flash is present in both pages.
Check the controller code for the same and verify what should be in the flash on that page.
Also, while there is no hard and fast rule, it is strongly advised to use only one template / view engine (erb or haml) in a single application.

On the Forgot Password page, is the flash object being set and the page then rendered, or is it being set and then a redirection to the page happening?
The normal use case for flash is that you assign to it and then redirect to another page where flash is present. If you want to use flash and then display it's contents in the same action (such as then rendering a template)
Instead of writing (e.g.)
flash[:notice] = 'Foo Bar'
You write
flash.now[:notice] = 'Foo Bar'

Related

Rails Devise "You need to sign in or sign up before continuing"

everybody.
I was using Devise for authentication in Rails 4 and got some troubles with Devise. When I enter the link: http://yourdomain.com:3000/users/edit.535db919486f611779000000 , it just render the text "You need to sign in or sign up before continuing." without rendering layout, instead of redirect to login page (see attachment)
I guess Rails understand the numeric after "edit." is format and it didn't know how to render it.
What I want is when user enter any link without logged in, it will redirect to login page. Could anyone help me?
With this link, it throw an unknown format exception.
Your problem is to do with the passing of a value after . - EG edit.234234324 or login.23424234
As you can see from your screenshot, you're receiving the error because Rails is treating the number as a format (in the same way it would treat .html, .js or .json as formats)
I don't know why it works for edit, but it looks like it's rendering json to me, probably because it's confused with the type of format you've sent
The way to fix this is to get your config/routes.rb & URLs fixed
You've not detailed how you're sending the numbered requests to your URL helper, but if you're requesting pure URLS, you need to remove the number from the end:
localhost:3000/users/login
localhost:3000/users/edit
These are the URLs which should load (with no numbers)
I would imagine you are getting the error because you're calling the devise url helpers like this:
<%= link_to "login", user_new_session_path(some_value) %>
You just need to use user_new_session_path

How can we circumvent these remote forms drawback?

In an effort to have everything translateable in our website ( including the error messages for the validations ), we switched almost all of our forms to remote forms. While this helps with the ability to translate error messages, we have encountered other problems, like:
if the user clicks on the submit button multiple times, the action gets called multiple times. If we have a remote form for creating a new record in the database, and assuming that the user's data is valid, each click will add a new object ( with the exact same contents ). Is there any way of making sure that such things cannot happen?
Is there somewhere I could read about remote forms best practices? How could I handle the multiple clicks problem? Is switching all the forms to remote forms a very big mistake?
There is a rails 3 option called :disable_with. Put this on input elements to disable and re-label them while a remote form is being submitted. It adds a data-disable-with tag to those inputs and rails.js can select and bind this functionality.
submit_tag "Complete sale", :disable_with => "Please wait..."
More info can be found here
Easy, and you can achieve that in many ways depending your preferences:
Post the form manually simply using an ajax request and while you wait for the response disable/hide (or whatever you need) the form to ensure the user can't keep doing posts as crazy. Once you get the response from the server, again you can allow the user to post again (cleaning the form first), or show something else or redirect it to another page or again whatever you need.
Use link_to :remote=>true to submit the form and add a callback function to handle the response and also to disable/hide (or whatever you need) the form when it's submitted
Add a js listener to the form to detect when it's submitted and then disable/hide/whatever the form
As you see, there are lots of different ways to achieve what you need.
EDIT: If you need info about binding or handling a form submit from js here you'll find very easy and interesting examples that may help you to do what I suggested you! jQuery Submit
I have remote forms extensively myself, and in most cases I would avoid them. But sometimes your layout or UX demands for on-the-fly drop-down forms, without reloading or refreshing the complete page.
So, let me tackle this in steps.
1. Preventing Normal form double-post
Even with a normal form, a user could double-click your button, or click multiple times, if the user does not get a clear indication that the click has been registered and the action has started.
There are a lot of ways (e.g. javascript) to make this visible, but the easiest in rails is this:
= f.button :submit, :disable_with => "Please wait..."
This will disable the button after the first click, clearly indicating the click has been registered and the action has started.
2. Handling the remote form
For a remote form it is not that much different, but the difference most likely is: what happens afterward ?
With a remote form you have a few options:
In case of error: you update the form with the errors.
you leave the form open, allowing users to keep on entering the data (I think this is your case?)
you redirect the users to some place.
Let me handle those cases. Please understand that those three cases are completely standard when doing a normal form. But not when doing a remote call.
2.1 In case of error
For a remote form to update correctly, you have to do a bit more magic. Not a lot, but a bit.
When using haml, you would have a view called edit.js.haml which would look something like
:plain
$('#your-form-id').replaceWith('#{j render(:partial => '_form') }');
What this does: replace the complete haml with only the form. You will have to structure your views accordingly, to make this work. That is not hard, but just necessary.
2.2 Clearing the form
You have two options:
* re-render the form completely, as with the errors. Only make sure you render the form from a new element, not the just posted one!!
* just send the following javascript instead:
$('#your-form-id').reset();
This will blank the form, and normally, that would effectively render any following clicking useless (some client validation could block posting until some fields are filled in).
2.3 Redirecting
Since you are using a remote form, you can't just redirect. This has to happen client-side, so that is a tad more complicated.
Using haml again this would be something like
:plain
document.location.href = '#{#redirect_uri}';
Conclusion
To prevent double (triple, quadruple, more) posts using remote forms you will have to
disable the button after first click (use :disable_with)
clear the form after succesful submission (reset the form or render with a new element)
Hope this helps.
The simplest solution would be to generate a token for each form. Then your create action could make sure it hasn't been used yet and determine whether the record should be created.
Here's how I would go about writing this feature. Note that I haven't actually tested this, but the concept should work.
1.
Inside the new action create a hash to identify the form request.
def new
#product = Product.new
#form_token = session["form_token"] = SecureRandom.hex(15)
end
2.
Add a hidden field to the form that stores the form token. This will be captured in the create action to make sure the form hasn't been submitted before.
<%= hidden_field_tag :form_token, #form_token %>
3.
In the create action you can make sure the form token matches between the session and params variables. This will give you a chance to see if this is the first or second submission.
def create
# delete the form token if it matches
if session[:form_token] == params[:form_token]
session[:form_token] = nil
else
# if it doesn't match then check if a record was created recently
product = Product.where('created_at > ?', 3.minutes.ago).where(title: params[:product][:title]).last
# if the product exists then show it
# or just return because it is a remote form
redirect_to product and return if product.present?
end
# normal create action here ...
end
Update: What I have described above has a name, it is called a Synchronizer (or Déjà vu) Token. As described in this article, is a proper method to prevent a double submit.
This strategy addresses the problem of duplicate form submissions. A synchronizer token is set in a user's session and included with each form returned to the client. When that form is submitted, the synchronizer token in the form is compared to the synchronizer token in the session. The tokens should match the first time the form is submitted. If the tokens do not match, then the form submission may be disallowed and an error returned to the user. Token mismatch may occur when the user submits a form, then clicks the Back button in the browser and attempts to resubmit the same form.
On the other hand, if the two token values match, then we are confident that the flow of control is exactly as expected. At this point, the token value in the session is modified to a new value and the form submission is accepted.
I hate to say it, but it sounds like you've come up with a cure that's worse than the disease.
Why not use i18n for translations? That certainly would be the 'Rails way'...
If you must continue down this route, you are going to have to start using Javascript. Remote forms are usually for small 'AJAXy things' like votes or comments. Creating whole objects without leaving the page is useful for when people might want to create lots of them in a row (the exact problem you're trying to solve).
As soon as you start using AJAX, you have to deal with the fact that you'll have to get into doing some JS. It's client-side stuff and therefore not Rail's speciality.
If you feel that you've gone so far down this road that you can't turn back, I would suggest that the AJAX response should at least reset the form. This would then stop people creating the same thing more than once by mistake.
From a UI/UX point of view, it should also bring up a flash message letting users know that they successfully created the object.
So in summary - if you can afford the time, git reset and start using i18n, if you can't, make the ajax callback reset the form and set a flash message.
Edit: it just occurred to me that you could even get the AJAX to redirect the page for you (but you'd have to handle the flash messages yourself). However, using a remote form that then redirects via javascript is FUGLY...
I've had similar issues with using a popup on mouseover, and not wanting to queue several requests. To get more control, you might find it easier to use javascript/coffeescript directly instead of UJS (as I did).
The way I resolved it was assigning the Ajax call to a variable and checking if the variable was assigned. In my situation, I'd abort the ajax call, but you would probably want to return from the function and set the variable to null once the ajax call is completed successfully.
This coffeescript example is from my popup which uses a "GET", but in theory it should be the same for a "POST" or "PUT".
e.g.
jQuery ->
ajaxCall = null
$("#popupContent").html " "
$("#popup").live "mouseover", ->
if ajaxCall
return
ajaxCall = $.ajax(
type: "GET"
url: "/whatever_url"
beforeSend: ->
$("#popupContent").prepend "<p class=\"loading-text\">Loading..please wait...</p>"
success: (data) ->
$("#popupContent").empty().append(data)
complete: ->
$"(.loading-text").remove()
ajaxCall = null
)
I've left out my mouseout, and timer handling for brevity.
You can try something like that for ajax requests.
Set block variable true for ajax requests
before_filter :xhr_blocker
def xhr_blocker
if request.xhr?
if session[:xhr_blocker]
respond_to do |format|
format.json, status: :unprocessable_entity
end
else
session[:xhr_blocker] = true
end
end
end
Clear xhr_blocker variable with an after filter method
after_filter :clear_xhr_blocker
def clear_xhr_blocker
session[:xhr_blocker] = nil
end
I would bind to ajax:complete, (or ajax:success and ajax:error) to redirect or update the DOM to remove/change the form as necessary when the request is complete.

Rails validation

I am suffering a issue with rails server side validation. Can some one help me out from this?
situation is :
I am creating dynamic for and its elements also dynamic.My application will generate the some HTMl code. Which can we use in any form or blog..
I applying the server side validation. But due to dynamic elements .I am not able to store the last entered value in to the elements. AS we normally does in PHP if user input something wrong we don't put the field empty. So I need to find a mechanism which fills the older values into the elements,If something went wrong.
This is the code into controller which is I'm using to show the form :
render :layout => false,:template=>'buildders/rander_form'
and view of rander_form.html.erb has
<%= render :file=>RAILS_ROOT+'/public/forms/form_'+#form_name+'.html.erb' %>
where #form_name is a dynamic form name(which have HTML code).
Can some one help me?
don't put erb files in public, people can download them by entering the file path in the url
also why not move that code out of the erb template into the controller?

Can I show an erb template in facebook page tab?

I am trying to display an erb template inside a facebook page tab. I am successful in doing so using wordpress, but with rails I am getting this error.
FBML Error: illegal tag "body" under "fb:tab-position"
The output of wordpress and rails are exactly similar. They are generating the same html. While in case of wordpress the contents are getting displayed in tabs, in case of rails it throws an error.
Has anyone successfully implemented a facebook app with page tabs using rails.
Is your template being rendered with a layout? Usually the layout would have head and body tags, which you don't want in your facebook content as it's in the context of a page (facebook) that already defines the head and body. To render a page without layout pass the :layout => false option to your render call.
You are most likely getting an error and the body tag is getting in there from the 500.html or the 404.html.
I tried a million things and I found that I had an invalid authenticity token. To see if this is your issue try:
skip_before_filter :verify_authenticity_token
In your controller that is rendering the view.
As the error message says, in a tab you can't have a 'body' tag. Are you 100% sure the Rails output doesn't somehow have it?
Basically you have to supply Facebook a stripped down HTML as they have their own 'head' and 'body' tags.

Prevent Flash-Message showing up twice (on page with error and on next page)

If there is an error in a form my grails application this results in a flash message. If I then go to another page, the (old) flash message shows up again on the new page.
How do I prevent this?
try using request.message, it act the same way as flash.message but will only stay on for on long enough to be displayed once.
controller:
request.message = message;
and on gps you use it like you wold with flash.message:
<g:if test="${request.message }"><br>
<div class="message">${request.message}</div> </g:if>
I would say if the message is for request only, use request.message. If a redirect could be involved, use flash and then clear the flash message after displaying it in the gsp:
<div class="message">
${flash?.message}
</div>
<%
// Prevent flash messages displaying twice if there is no redirect
flash.message = null
%>
I would have all this in a standard template that you use for displaying messages.
One thought would be to clear the flash message on the first page when an error is detected.
Not sure if the request.message route is still an option in the newer version of grails as I tried this and it didn't work for me.
A method I found to avoid showing the message twice is to set a message using a more specific key in flash such as:
Controller:
flash.specificKeyForControllerAndAction = "Some message"
GSP:
<g:if test="${flash.specificKeyForControllerAndAction}">
<div class="message">${flash.specificKeyForControllerAndAction}</div>
</g:if>
Obviously the key could be anything you would like, but make sure your other views aren't checking for the same key or else the message will display again.
quote from grails documentation
http://docs.grails.org/3.1.1/ref/Controllers/flash.html
The flash object is a Map (a hash) which you can use to store key value pairs. These values are transparently stored inside the session and then cleared at the end of the next request.
This pattern lets you use HTTP redirects (which is useful for redirect after post) and retain values that can be retrieved from the flash object.
You must remember how works redirect http://grails.asia/grails-redirect-vs-forward
When you do a redirect, there is a go back to the client browser, and the browser call the url it received, then this call is the "next" request after adding flash message.
Then you should add a flash message before a redirect. Because this flash message is cleared at the end of the next request. Or if you do not use a redirect, and just do a simple forward (a simple return render of your gsp for example) there is no other request after adding the flash message. Thus the next request will be when you access another link.
It is only at the end of this next request, then after the gsp rendering, that the flash message will be cleared from session by grails framework.
To conclude :
if you want to display a message when you do a redirect use flash message. It's automatically cleared by the framework.
if you want to display a message when you do a forward you can use a solution as stated by fonger (add a message in the request).

Resources