Return "title" column if "caption" column is empty?

Hi all

Oh my god, this really shouldn't be a tough one, but I just don't get it. :wink:

class Page < ActiveRecord::Base   def caption     caption ? caption : title   end end

I want to return the content of the title column when the caption column is empty:

p.caption # Caption is not empty # => "caption"

p.caption # Caption is empty # => "title"

Not astonishing, I get a StackLevelTooDeep Exception with my "solution" above... But how can I do it right?

Thanks a lot... My brain is just a bit wrecked today... Josh

This will produce an infinite loop. I think you want something more like

self.caption ? self.caption : self.title

But honestly I'd rename the method to something else for clarity.

Agreed. At some point you're going to want to access 'caption' directly and the above won't let you do that.

Plus your team might not realize you're adding magic.

I've always gone with "preferred"... that is..

def preferred_caption    # code to get me the ideal caption for the fields available end

That helps remind me that I'm not necessarily getting back the caption itself, but the ideal caption for the given situation.

It's worked well for me so far.


Use read_attribute(:caption).

Thanks for your useful hints, guys. :slight_smile:

super might work too

  def caption     super ? super : title   end

Mauricio Szabo wrote:

super might work too

  def caption     super ? super : title   end

But it won't, because caption is not defined on the superclass.

On Oct 7, 5:26�pm, Joshua Muheim <>


Have you tested it? I tried on a test application, and it works...

Mauricio Szabo wrote:

Have you tested it? I tried on a test application, and it works...

Hmm. Maybe ActiveRecord's method_missing trickery strikes again...

On Oct 8, 9:06�am, Marnen Laibow-Koser <rails-mailing-l...@andreas-


Also I am not sure what rails default is when you just add a "?"....does it only fail if caption is nil?

I like to do something like this in these scenarios:

def the_caption   self.caption.blank? title : caption end

I haven't used read_attribute yet but from the docs it might look something like this

def caption       caption = read_attribute(:caption)       caption.blank? self.title : caption end

You get the idea though....just wanted to mention the "blank" part because if your caption is somehow set to " " I am guessing you want the title returned.

def caption   self[:caption] || title end

@Joshua - FYI self[:caption] <=> read_attribute(:caption)

@Chris - ...and I am guessing interchangeable with self.caption

Afaik it has nothing to do with method missing magic. Its just that if you overwrite a method, a call to super invokes the original method. AR injects accessor methods for every table column into the class.