Attribute or instance method or what?


#1

Hi!

Uhm are attributes just something like additional members of a class,
other than those that come from the names of columns in the table?

I’ve got images table, which has ‘name’ column. I’ve added support for
creating thumbnails out of uploaded pictures and i’d like to have an
easy way of accessing them in my views.

How to do it? I.e. my image has name ‘1-13.jpg’ and thumbnail will have
‘1-13-thumb.jpg’. Do i have to create additional attribute thumbnailname
and somehow set it automatically based on ‘name’ value, so it will be
available for an instance variable of my image class, or create a helper
method for image class or…?


#2

CzeÅ?Ä? Szymek :slight_smile:

On 08/03/06, szymek removed_email_address@domain.invalid wrote:

How to do it? I.e. my image has name ‘1-13.jpg’ and thumbnail will have
‘1-13-thumb.jpg’. Do i have to create additional attribute thumbnailname
and somehow set it automatically based on ‘name’ value, so it will be
available for an instance variable of my image class, or create a helper
method for image class or…?

The simpliest way would be to provide additional getter:

class Image
def thumbnail_name
self.name.gsub(/.jpg$/, ‘-thumb.jpg’)
end
end


#3

On Mar 8, 2006, at 10:19, Łukasz Piestrzeniewicz wrote:

method for image class or…?

The simpliest way would be to provide additional getter:

class Image
def thumbnail_name

end
end

And if you needed the thumbnail name in SQL land as well then write a
custom name setter that delegates to AR this way:

class Image < ActiveRecord::Base
def name=(n)
write_attribute(:name, n)
write_attribute(:thumbnail_name, n.gsub(/.jpg$/, ‘-thumb.jpg’))
end
end

– fxn


#4

Czesc!

Dzieki za odpowiedz!.. i mean, thanks for your answer :slight_smile:

Previously i had name2thumbname as class method. Now i’ve changed
everything to instance methods and it works great, but i’ve got one more
question:

I’m adding new images to the database like this (in a loop):
@property.images << Image.new(:image_url => image_filename)

Is it possible to get id of new image without searching for it in the
database? Maybe << method returns new id?

Because since i’ve changed everything to instance methods now i add the
image to the database and in the next line i search for it by the
filename to get its instance. It works, but maybe there’s a better way.