Capitalizing an attribute - view, controller, or model?

The users will enter students names on forms. How do I intercept the
first and last names and have them stored capitalized when the user
inputs them in lower case?

Do I mess with the form html, skipping form_for helpers and using
conditional clauses in the view?

Do I need to separate out the individual attribute and update it
separately in the controller actions that save/updates the
record?(instead of the blanket object.update_attributes(params[:object])
)

Or, and I think this is what I seem to recall seeing, can I create a
definition in the model that automatically capitalizes given attributes?

I would like code below to work in the Student model(unfortunately its
not working!(and creates a “stack level too deep” error if i leave out
“self”))

def self.first_name
first_name.capitalize
end

Am I close?

On Dec 7, 2007 12:21 PM, Tom N. [email protected]
wrote:

record?(instead of the blanket object.update_attributes(params[:object])
first_name.capitalize
end

Am I close?

Posted via http://www.ruby-forum.com/.

To overwrite an accessor setup by AR you need to use a different syntax

def first_name
self[:firstname] = self[:firstname].capitalize_first_letter_method
end

You know though you can do that with css…

HTH

hmm,

I don’t think I really hope to change just what is displayed, or change
what is pulled out over and over again (thats what the accessor would
do?)

I’d prefer to change what is stored ? (thanks for pointing out the
correct way of changing what is retrieved though!)

There must be an idiomatic way of filtering and altering form data going
into records. Is it just to individually set each attribute in the
controller?

Thanks Steve!

should have thought of before filters before ; ) … guess thats why
they’re there for.

On Dec 6, 2007, at 5:46 PM, Tom N. wrote:

There must be an idiomatic way of filtering and altering form data
going
into records. Is it just to individually set each attribute in the
controller?

class MyModel < AR::Base
before_save :capitalize_fields
before_update :capitalize_fields

private
def capitalize_fields
[:first_name, :last_name].each {|field| self[field] = self
[field].capitalize}
end
end

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