Active Admin - flash messages not appearing on page - ruby-on-rails

I am trying to display a notice after redirecting to a page but it doesnt appear.
Here is the redirect -
redirect_to :action => :index, :notice => "My redirect"
You can see the message in the url but there doesnt seem to be any code inside active admin to display it.
Any ideas how to render it inside active admin ?

There seems to be some issue that I haven't tracked down yet, but if you are looking for a work-around until then, this is what I did:
member_action :test do
flash[:notice] = "This is a test notice!"
redirect_to :action => :index
end
The problem that I am seeing is that when you put :notice in the redirect_to method, the notice message is url encoded and added to the URL
member_action :test do
redirect_to :action => :index, :notice => "This is a test notice!"
end
results in
/admin/model?notice=This+is+a+test+notice!
which is less than ideal. I noticed a change to the active_admin documentation that includes putting {} around the first parameter to redirect_to to fix this problem, however, for me, this results in an error.
member_action :test do
redirect_to {:action => :index}, :notice => "This is a test notice!"
end
which results in
syntax error, unexpected tASSOC, expecting '}'
redirect_to {:action => :index}, :notice => "This...
I posted a comment on that particular pull request # active_admin on github and hopefully someone might have another suggestion, since I am stumped.
In any event, maybe one of these solutions will work for you. Good luck.

Active Admin doesn't render flash messages, it believes they are rendered in t layout renders them.
When you run active_admin:install generator it mentions that:
$ rails g active_admin:install
...
Some setup you must do manually if you haven't yet:
...
3. Ensure you have flash messages in app/views/layouts/application.html.erb. For example:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

Related

flash notice is lost on redirect, how to find out what's removing it?

There are many posts on SO about this ( respond_with redirect with notice flash message not working Why is :notice not showing after redirect in Rails 3, among others) , I've read at least 4 and still can't solve this issue.
I've got a portion of my site that lets people do some things before they create an account. I prefer this from a UX perspective. So they're allowed to do X and Y then they get redirected to the "Create account" page (uses Devise).
The redirect looks like:
if userIsNew
... stow information in a cookie to be retrieved later ...
redirect_to "/flash", flash[:notice]
=> "Ok, we'll get right on that after you sign up (we need your email)."
and return # this has to be here, since I'm terminating the action early
end
So "/flash" is a plain page that I made to test this. It doesn't do anything, has no markup of its own, just has the basic html from the application.html, which has this line in the body:
<% if flash[:notice] %>
<p><%= notice %></p>
<% else %>
No notice!
<% end %>
It says 'No notice' every time.
I have tried:
adding in a flash.keep to my before_filter in the static controller
using :notice => instead of flash[:notice] =>
putting the notice in a cookie and pulling that text out of the cookie and into a flash in the before_filter of my application controller
redirect_to :back with the flash[:notice] =>
It's either
flash[:notice] = 'blablabla'
redirect_to foo_url
or
redirect_to foo_url, notice: 'blablabla'
I'm overriding ApplicationController#redirect_to to call flash.keep so that any messages are persisted on redirect without having to explicitly call flash.keep in my controller actions. Works well so far. Haven't had a scenario yet where unwanted messages are persisted.
class ApplicationController < ActionController::Base
def redirect_to(*args)
flash.keep
super
end
end
Let me know if there are any scenarios where this isn't a good solution.
I have been fighting with the same problem for some time and none of the posts seemed to help.
It turns out that - like usually it happens - the the problem was in my code. I did have a "redirect_to" that I forgot about, which was clearing the flash.
Namely, "root_path" for me was served by the StaticPagesController's home method. "home" was doing some checks and then redirecting you to the user_path.
In my code I had in numerous places
redirect_to root_path, :flash => {error: #error}
These redirects were never displaying the flash because my hidden "home" controller serving the "root_path" was making another redirect that cleared the flash.
Therefore my problem was solved when i added the "flash.keep" in my "home" controller method
def home
if current_user
#user = current_user
flash.keep
redirect_to #user unless #user.no_role?
end
end
Faced the same problem, flash just disappeared after any redirect, nothing helped, then, I found that it was switched off...
Check your /config/application.rb for this:
config.middleware.delete ActionDispatch::Flash

Retaining a URL on a failed form submission in Ruby on Rails

I'm currently working my way through various Rails tutorials, but all seem to recommend that a failed form submission should use a render to output the form with the errors. For example, the create method looks like this:
def create
#user = User.new(params[:user])
if #user.save
flash[:success] = "Welcome to the Sample App"
redirect_to #user
else
#title = "Sign up"
render 'new'
end
end
This has the desired effect, but means that if I have a new user form at http://localhost:3000/users/new and an error occurs, I get the same form with errors at http://localhost:3000/users
Is there a way to make sure I go to http://localhost:3000/users/new instead?
I thought about using a redirect instead of render 'new', but this would cause problems with displaying the form errors. Someone on the Rails IRC directed me to a way of doing clientside validations, but that seems like it dodges the issue.
I had a similar problem with my user signup form. Since I do not use RESTful routes there, I was able to solve it with the following routes:
resources :users, :except => [:new, :create] do
...
end
get "/signup" => "users#new"
post "/signup" => "users#create"
and in the new form:
form_for #user, :url => signup_path do ...
Try redirect_to :action => 'new' instead of just rendering, this will retain the url, but the information about errors will be lost (unless you put it in flash).
The other option is to submit the form to the URL that is used for displaying it. At the beginning of the action you check whether there is some data you need to process. If the processing goes fine, you redirect_to somewhere else, otherwise you do nothing - the form gets displayed, together with all the errors. This, I suppose, is not very Railsy, but it should work as you want.
Sorry for being late (a mere 6 years) to the party but somehow this seems to be an issue with Turbolinks.
See these issues here and here.

How do I maintain the same controller & action in a page URL upon re-rendering an action in Rails?

I am using AuthLogic to authenticate users in my rails app. That part is set up and workign properly.
I have the following route defined:
map.login '/account/login', :controller => :user_sessions, :action => :new
Calling rake routes returns what I expect:
login /account/login {:controller=>"user_sessions", :action=>"new"}
When someone submits a login, it calls UserSessionsController.create:
def create
#user_session = UserSession.new(params[:user_session])
if #user_session.save
flash[:notice] = "Login successful!"
redirect_back_or_default account_url
else
render :action => :new
end
end
If #user_session.save fails, the appropriate error messages appear on the screen. However, the browser URL also changes to "http://localhost:3000/user_session" instead of staying on "http://localhost:3000/account/login".
I assume the problem is what I am feeding to the render method. What should I be feeding it?
This is actually the intended behavior for this process. In a standard scaffolded RESTful controller, a validation error in the create and update actions will simply render the original template without redirecting. This results in what you are seeing – the new template will be displayed with the create action's URL in the URL bar. The reason for this is that in order to display information to the user about what errors occurred, the view must have access to the invalid model object, which is #user_session in your case.
You can use redirect_to instead of render if you want to force a redirect to the original URL, but this will cause you to lose information about the errors. You would need to manually persist the errors in the session, which would be messy. My advice is not to worry about the fact that the URL doesn't match that of the original as this is pretty standard in all Rails apps.
Just adding solution for Rails 4 (based on Shaun's answer here):
Add new route to routes file:
post '/carts/new' => 'carts#create', as: :create_post
Add url: create_post_path to form tag
Done.
After further digging, I found the solution in another StackOverflow question: Use custom route upon model validation failure
I simply modified my routes to add a new one for posing to '/account/login':
map.login '/account/login', :controller => :user_sessions, :action => :new, :conditions => {:method => :get}
map.login_post '/account/login', :controller => :user_sessions, :action => :create, :conditions => {:method => :post}
Then, I updated my view to utilize the new route:
<% form_for #user_session, :url => login_post_path do |f| %>
This works perfectly. A failed login gives the appropriate error messages and maintains the '/account/login' URL.

Ruby on Rails: using method name 'request' in controller fails

I am at an absolute loss as to what I am doing wrong with the following code. I am trying to implement a messaging system within my application, but want it to be handle different types of messages. In this case, I want to create a "request" message of ':message_type => 1'.
Instead of using forms as I usually have, I want to make this instance the moment the link is clicked. Here is how I have it set up in the show erb file for "user":
<%=link_to "Send friend request", :action=>"request", :controller => "messages", :id => #user.id %>
and in the controller:
def request
#message = Message.new(:sender_id => current_user.id,:user_id => params[:id],:message_type => 1)
if #message.save
flash[:notice] = 'Message was successfully created.'
redirect_to message_path(#message)
else
redirect_to message_path(#message)
end
end
This results in the following error message: undefined method `rewrite' for nil:NilClass with the trace looking like
c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/whiny_nil.rb:52:in `method_missing'
c:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:634:in `url_for'
(eval):16:in `message_path'
app/controllers/messages_controller.rb:11:in `request'
I have used map.resources :messages in the routes.rb file, and done the appropriate :has_many and :belongs_to associations in the models of user and message.
EDIT: Something else to note is that the save IS succeeding, as once the root address is manually inputted into the address bar, the "flash" notice is shown saying that the save was made. Using the development console it is indeed there, so there's something messed up with the redirect.
You might want to rename the action, I am quite sure that request means something in the controller.
Why dont you rename the action from request to create, and see if it helps.
So the code will be:
In the view
<%=link_to "Send friend request", :action=>"create", :controller => "messages", :id => #user.id %>
In the controller
def create
#message = Message.new(:sender_id => current_user.id,:user_id => params[:id],:message_type => 1)
if #message.save
flash[:notice] = 'Message was successfully created.'
redirect_to message_path(#message)
else
redirect_to message_path(#message)
end
end
Check your logs more closely, and you'll probably find that your save is failing. Not sure which line is #11, but I would guess that it's in your else block, which tries to build a path for a #message object with a nil ID (it hasn't been saved).

Rails 2.3.5: flash[:notice] disappears after redirect_to call

Here I've got two controller methods:
def invite
if request.post?
begin
email = AccountMailer.create_invite(#user,url)
AccountMailer.deliver(email)
flash[:notice] = "Invitation email sent to #{#user.email}"
rescue
#mail delivery failed
flash[:error] = "Failed to deliver invitation"
end
redirect_to :action => :show, :id => #user.id
end
end
and
def show
#title = "User #{#user.full_name}"
end
The problem is, when I send an invitation, and get redirected to ./show, I see no messages at all. If I change redirect_to to render, the message appears. Still, isn't it intended for flash to work in the immediate subsequent requests?
BTW, I'm using Rails+Passenger setup, could it be so that redirected request goes to another application instance?
The rescue block is setting flash[:error], not flash[:notice]. Is your view actually rendering both?
Googled better and found this discussion:
http://www.mail-archive.com/activescaffold#googlegroups.com/msg04284.html
The solution is there: replace the plugin with
script/plugin install git://github.com/ewildgoose/render_component.git -r rails-2.3 --force
Though I don't use ActiveScaffold, there is some legacy code that depends on render_component plugin. Updating plugin to branch version worked, though I'm planning to get rid of it completely.

Resources