[LRUG] Query about ActiveRecord

Paul Doerwald paul at liquidmedia.ca
Fri Aug 17 11:15:50 PDT 2007


Hi John,

My approach is a bit simpler than the others, which is making me  
start to worry whether I'm doing the right thing (!). YMMV, but I use:

class Cycle < ActiveRecord::Base
   # I don't need to redefine 'def pattern', b/c it works out of the box

   def pattern=(new_pattern)
     self[:pattern] = new_pattern
     # do the other stuff you want to do
   end
end

Paul.


On 17-Aug-07, at 1:58 PM, John Winters wrote:

> 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
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org




More information about the Chat mailing list