Providing action with: notification, which depends on the URL parameter

I have an “approval” of an action that displays a view that displays some content from a model (class). In the view, I have link_to that calls accept with the URL parameter (: id). After the accept action has completed (set to true), I would like to display approval again with the message ("Saved!"). However, unlike the static login page, the approval action requires a parameter on the first call. The second time it is displayed, a runtime error occurs (obviously). What is the best way to invoke flash notification approval ?

 def approval @c = Class.find(params[:id]) end def accept @c = Class.find(params[:id]) @c.approve = true @c.save render 'approval', :notice => "Saved!" end 
+8
ruby-on-rails ruby-on-rails-3
source share
3 answers

change this render 'approval', :notice => "Saved!" on

 flash[:notice] = "Saved!" redirect_to :back 
+7
source share

You can use FlashHash#now to set a notification for the current action.

 flash.now[:notice] = 'Saved !' render 'approval' 

http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-now

+3
source share

Exceprt from: http://www.perfectline.ee/blog/adding-flash-message-capability-to-your-render-calls-in-rails

Now the general pattern in the controllers is as follows:

 if @foo.save redirect_to foos_path, :notice => "Foo saved" else flash[:alert] = "Some errors occured" render :action => :new end 

What I want to do is:

 if @foo.save redirect_to foos_path, :notice => "Foo saved" else render :action => :new, :alert => "Some errors occured" end 

Adding this function is actually quite simple - we just need to create code that extends the rendering function. This next piece of code actually extends a module that contains functions for call forwarding.

 module ActionController module Flash def render(*args) options = args.last.is_a?(Hash) ? args.last : {} if alert = options.delete(:alert) flash[:alert] = alert end if notice = options.delete(:notice) flash[:notice] = notice end if other = options.delete(:flash) flash.update(other) end super(*args) end end end 
+1
source share

All Articles