How to simulate a column that do not exists in a model

Hello there…

what i am trying to do, is to consider a new column in my model, a
column
that do not exist in the database, and will not be created.

imagine, for instance, this case:

I have a table that store a number and a string, lets call it ‘words’


words

int times(PK)
char name

imagine Word as an instance of the model, i will have access to these:
Word.times
Word.name

what if i wanted a new column, some like
Word.complete

imagine that this column would store that ‘char’ for many times as is
defined int the ‘times’ column…
like this

Word.times = 3
Word.name = a
Word.complete = aaa

got it?

i wont store that data, but generate it based on the data that is
stored.

any idea???

did any of you guys see this situation before???


Lucas Franceschi
Desenvolvedor
SGI Sistemas
(049) 9922-3360

lucas franceschi wrote:

Word.complete = aaa

Word is the model class - it doesn’t store values.

If word is an instance, simply write:

word[:complete] = aaa

you didn’t get it…

the point is… i want

Word.complete

to already be defined, so that in the controller i could use the
“complete”
column as if it was a real column…

Lucas Franceschi
Desenvolvedor
SGI Sistemas
(049) 9922-3360

correction - you will need to check that both name and times_repeated
are not nil

def complete
self.name * self.times_repeated if self.name && self.times_repeated
end

strictly speaking the “self.” isn’t needed either, but it does make
the intention clearer…

just look up attr_accessor method, if used within a model on a non
existant field in the model, it will create a “pseudo” field. Do not
forget to make accessible.

On 31 August 2010 19:48, lucas franceschi [email protected] wrote:

Word.times = 3
Word.name = a
Word.complete = aaa
got it?
i wont store that data, but generate it based on the data that is stored.
any idea???
did any of you guys see this situation before???

once or twice…

what you’re after is a “method”…

(you may run into trouble if you try to call your column ‘times’, I’ll
use ‘times_repeated’ in this example)

word.rb

def complete
self.name * self.times_repeated if self.name
end

I recommend going through some Ruby tutorials - the “Ruby for Rails”
book has a good coverage of getting started through to intermediate
use.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs