Adding flash message as render argument

48 views
Skip to first unread message

Tom Prats

unread,
Aug 7, 2016, 4:18:02 PM8/7/16
to Ruby on Rails: Core
Currently you can add a flash notice to your render call like so:

flash[:notice] = "Notice me!"
render :index

Similar to how it can be passed with redirect_to, I'd like to be able to pass it as an argument to render:

render :index, notice: "Notice me!"

I've been using a monkey patch to allow this, but if you think this is a valid feature, I'd love to write a pull request. Here's the code for the patch, I can't find where I got it, but I wasn't the original author:


Thanks,
Tom

Sean Linsley

unread,
Aug 7, 2016, 4:19:32 PM8/7/16
to rubyonra...@googlegroups.com
To prevent top-level variable congestion, this may be better:

render :index, flash: {notice: ‘hi’}


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-co...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Tom Prats

unread,
Aug 7, 2016, 4:34:04 PM8/7/16
to rubyonra...@googlegroups.com
Sean - I'd agree with that but I think it'd be good to have it consistent with redirect_to. 

DHH

unread,
Aug 8, 2016, 11:31:22 AM8/8/16
to Ruby on Rails: Core
The key purpose of the flash is to provide a variable that survives a redirect. I get that there may well be special circumstances that require setting the flash in the same request as the response is being sent from, but that's a pretty uncommon use case (or at least should be). So I think it's actually better that this is called out on a separate line, since it's somewhat abnormal. If the render call had it backed in, there'd be an implicit endorsement that using the flash in this manner is standard operating procedure.

But if your app does have this as a standard pattern, then all good with freedom patch! :D

Tom Prats

unread,
Aug 8, 2016, 1:19:44 PM8/8/16
to Ruby on Rails: Core
Thanks for you response. That makes a lot of sense. In this case I was using flash for notifications, which sometimes would need to be passed immediately, and sometimes held onto for the next request. In this case I think I'll stick with the freedom patch, but if flash and my notification functionality diverge in the future, I'll know why. Thanks for you help!

--

Alexey Nikolaev

unread,
Sep 1, 2016, 5:50:34 AM9/1/16
to Ruby on Rails: Core
In case if you want to display flash message immediately on render you can use flash.now to set the message:

flash.now[:notice] = 'Show me without redirect'


Very easy!
Reply all
Reply to author
Forward
0 new messages