Freelancing Gods 2014

God
05 Nov 2007

Aliasing Actions in Rails

Tags:

Code snippet for application.rb that makes life just a little easier if multiple actions are doing exactly the same thing (both in the controller and the view):

def self.alias_action(existing, aliased)
  define_method(aliased.to_sym) do
    send(existing.to_sym)
    render :action => existing.to_s
  end
end

And then in the appropriate controller (where edit is an existing action, and show needs to be exactly the same):

alias_action :edit, :show

I know this is a specialised use – but perhaps someone else out there is doing something similar.

Comments

2 responses to this article

05 Nov 2007
Dr Nic said:

Hmm, I love where your heart is at. Perhaps

def edit; show; end

Gets the trick done too :)

05 Nov 2007
pat said:

Ah, not quite Nic – as the view for the existing action needs to be rendered as well – which is one extra line: render :action => "show" for your example.

But yeah, it’s not saving many lines of code, I just find it a little more elegant.

Leave a Comment

Comments are formatted using Textile. Please be respectful of others when posting comments. Be nice.

RssSubscribe to the RSS feed

Related Links

Related Posts

About Freelancing Gods

Freelancing Gods is written by , who works on the web as a web developer in Melbourne, Australia, specialising in Ruby on Rails.

In case you're wondering what the likely content here will be about (besides code), keep in mind that Pat is passionate about the internet, music, politics, comedy, bringing people together, and making a difference. And pancakes.

His ego isn't as bad as you may think. Honest.

Here's more than you ever wanted to know.

Ruby on Rails Projects

Other Sites

Creative Commons Logo All original content on this site is available through a Creative Commons by-nc-sa licence.