[LRUG] Query about ActiveRecord
John Winters
john at sinodun.org.uk
Fri Aug 17 10:58:48 PDT 2007
I'm still plodding along learning about Rails and I've got a query about
ActiveRecord. I think I've explained to myself what's happening (but
want to check that I've got it right) and I'm wondering whether there's
a better way of doing what I want to do.
I have a model called a cycle, and it has an attribute called a pattern.
It's just a string which the user enters and it's meant to be a fixed
length. If the user enters too short a string I want to pad it out to
the required length before it's saved to the database. The way I tried
to do it was by writing my own accessor functions like this:
class Cycle < ActiveRecord::Base
def pattern
@pattern
end
def pattern=(new_pattern)
#
# Pad new_pattern to required length if needed, and then...
#
@pattern = new_pattern
end
end
Obviously you have to use @pattern and not self.pattern or you end up
with a recursive call.
This ran OK, but the new value was not saved to the database. I'm
assuming I've broken things by writing my own accessor functions for a
database column item. Perhaps ActiveRecord doesn't realise the instance
variable has been updated? The way I've worked around it is to do:
class Cycle < ActiveRecord::Base
def mpattern
self.pattern
end
def mpattern=(new_pattern)
#
# Pad new_pattern to required length if needed, and then...
#
self.pattern = new_pattern
end
end
and then change the name of the field in the view from "pattern" to
"mpattern". This works, but strikes me as messy. Is there a more
rails-correct way of doing it?
TIA,
John
More information about the Chat
mailing list