Richard Schneeman wrote:
> 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??
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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---