Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering an action with :notice that depends on a URL param

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
like image 706
Jackson Henley Avatar asked Jun 27 '12 04:06

Jackson Henley


3 Answers

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

flash[:notice] = "Saved!"
redirect_to :back
like image 109
abhas Avatar answered Nov 15 '22 20:11

abhas


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

like image 40
tight Avatar answered Nov 15 '22 18:11

tight


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
like image 39
upisdown Avatar answered Nov 15 '22 19:11

upisdown