I have an action 'approval' that renders a view which displays some content from a Model (class). Within the view I have a link_to that calls accept
with a URL parameter (:id). After the accept
action completes (sets approve to true) I would like to render approval
again with a message ("Saved!"). However, unlike a static login page, the approval action requires a param the first time it is called. The second time it is rendered, an runtime error occurs (obviously). What is the best way to call approval
with the flash notice?
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
change this render 'approval', :notice => "Saved!"
to
flash[:notice] = "Saved!"
redirect_to :back
You can use FlashHash#now
to set the notice for the current action
flash.now[:notice] = 'Saved !'
render 'approval'
http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-now
Exceprt from: http://www.perfectline.ee/blog/adding-flash-message-capability-to-your-render-calls-in-rails
Now the common pattern in controllers looks like this:
if @foo.save
redirect_to foos_path, :notice => "Foo saved"
else
flash[:alert] = "Some errors occured"
render :action => :new
end
What I want to be able to do is this:
if @foo.save
redirect_to foos_path, :notice => "Foo saved"
else
render :action => :new, :alert => "Some errors occured"
end
Adding this functionality is actually pretty simple – we just have to create some code extending the render function. This next piece of code actually extends the module containing the functionality for the redirect calls.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With