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...? -- Posted via http://www.ruby-forum.com/.
Ćukasz Piestrzeniewicz
2006-Mar-08 09:19 UTC
[Rails] attribute or instance method or what?
Cze?? Szymek :) On 08/03/06, szymek <g0nzo@o2.pl> 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 -- ?ukasz Piestrzeniewicz http://ragnarson.blogspot.com
On Mar 8, 2006, at 10:19, ?ukasz Piestrzeniewicz wrote:> Cze?? Szymek :) > > On 08/03/06, szymek <g0nzo@o2.pl> 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 > > end > endAnd 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
Czesc! Dzieki za odpowiedz!... i mean, thanks for your answer :) 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. -- Posted via http://www.ruby-forum.com/.