# Best way to automatically format model entries

**URL:** <https://www.ruby-forum.com/t/best-way-to-automatically-format-model-entries/156412>\
**Category:** Rails\
**Created:** [December 26, 2008, 11:49pm UTC](https://www.ruby-forum.com/t/best-way-to-automatically-format-model-entries/156412 "2008-12-26T23:49:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [December 26, 2008, 11:49pm UTC](https://www.ruby-forum.com/t/best-way-to-automatically-format-model-entries/156412/1 "2008-12-26T23:49:59Z")

</div>

Using rails 2.1.0 I have a really nasty bit of code in my controller in  
my create action that i would like to move to my model:

params[:phrase][“word”] = params[:phrase][“word”].strip.squeeze(" ")  
if params[:phrase][“word”] != nil

params[:phrase][“second\_word”] =  
params[:phrase][“second\_word”].strip.squeeze(" ") if  
params[:phrase][“second\_word”] != nil

params[:phrase][“third\_word”] =  
params[:phrase][“third\_word”].strip.squeeze(" ") if  
params[:phrase][“third\_word”] != nil

@phrase = Phrase.new(params[:phrase])

What would be the best way to do this, I was thinking of putting it  
inside of a :before\_save function. But i’ve never written one before and  
didn’t know how to get the parameters from my recently saved phrase( how  
do I tell it to use the phrase i just created? @phrase.word ? ). What  
would you recommend??

---

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [December 28, 2008, 9:26pm UTC](https://www.ruby-forum.com/t/best-way-to-automatically-format-model-entries/156412/2 "2008-12-28T21:26:12Z")

</div>

Richard S. wrote:

> params[:phrase][“third\_word”] =  
> would you recommend??  
> Put something like this in a file in the lib directory:

class ActiveRecord::Base  
def self.blacken\_attrs(\*attrs)  
before\_validation \<\<-END  
#{attrs.inspect}.each do |attr|  
if v = send(attr)  
v.strip!  
v.squeeze!(’ ')  
end  
end  
END  
end  
end

Then in the Phrase model write

blacken\_attrs :word, :second\_word, :third\_word

–  
Rails Wheels - Find Plugins, List & Sell Plugins -  
[http://railswheels.com](http://railswheels.com)
