flyingarmadillo
flyingarmadillo

Reputation: 2139

before_save & before_create titleize trouble

I am developing a rails app and I am trying to titleize an attribute before it is saved or created. I am pretty sure I have done this correctly, however, whenever I try to create a new record in my rails console, the titleize is not taking place. Here is my model code:

class City < ActiveRecord::Base
  attr_accessible :name, :region_id

  belongs_to :region

  before_save :tileize_name
  before_create :tileize_name


  def tileize_name
    self.name.titleize
  end

end

When I read an attribute in my console, the titleize method works. For example:

Region.find(4).name
 => "arizona" 


Region.find(4).name.titleize
 => "Arizona" 

Am I missing something here?

Upvotes: 1

Views: 1700

Answers (3)

Ramsy de Vos
Ramsy de Vos

Reputation: 1072

Actually adding

before_save { self.chefname = chefname.titleize }

in "your_model.rb" would solve this problem.

so it would look like

class Chef < ActiveRecord::Base
  before_save { self.chefname = chefname.titleize }
end

Also it's worth taking a look at https://github.com/granth/titleize

Upvotes: 0

manishval
manishval

Reputation: 89

Or you can do this,

before_save { self.name.titleize! }

The bag operator changes and saves the value. Then you won't need before_create.

Upvotes: -1

BaronVonBraun
BaronVonBraun

Reputation: 4293

You're titleizing the name but not saving it.

string = "hello"
string.titleize
# => "Hello"
string
# => "hello"

string = string.titleize
# => "Hello"
string
# => "Hello"

You need to assign the titleized name to your name attribute.

def tileize_name
  self.name = self.name.titleize
end

Upvotes: 7

Related Questions