Modifying Model Output

Hi!

I’m a very-very new Ruby-on-Rails user even if I have some experience
with other Languages (mostly PHP, so this is my first real
object-oriented language)

My problem, newbie-ish as it is, is the following: I have a model,
Article, that returns Articles from the DB. Now, when a certain field of
the model (the intro text) contains no data, I want to fill it with a
truncated version of another field (the full text). So far, I have tried
adding the following to app/models/article.rb but it won’t work.

def self.intro
if self.intro == “”
self.intro = truncate(self.text)
self.intro
end
end

Any ideas why I get nothing here?

def self.intro defines a class method, not an instance method. Use def
intro instead. Something like this may be what you need:

def intro
value = read_attribute(:intro)
value.blank? truncate(text) : value
end

-Jonathan.

Thanks for the tip, I can’t get it to work as of yet, though.

There seemed to be a syntax error in your code, even though I couldn’t
locate it. When I rewrote it as follows, however, I only got back empty
strings when trying to display @articles[0].intro in my view.

def intro
value = read_attribute(:intro)
if value.blank?
value = read_attribute(:text)
end
value
end

I am not sure, but could it be that the code gets executed but the
returned value doesn’t get forwarded into @articles?

Indeed, it should have been:

def intro
value = read_attribute(:intro)
value.blank? ? truncate(text) : value
end

That should work …

-Jonathan.

That should work …

Yes it does indeed, thanks a lot! Could you maybe point me in the right
direction how to get the text from the DB? read_attribute(:text) doesn’t
work.

Actually, truncate may not be available in a model, try:

def intro
value = read_attribute(:intro)
value.blank? ? text : value
end

-Jonathan.

It works! You, sir, are a genius!

Using read_attribute(:contents) which is the REAL name of the table row.
hangs head in shame

Thanks :slight_smile:

Try read_attribute(‘text’).

-Jonathan.

Great. But I’m not a genius :wink:

-Jonathan.