views:

893

answers:

2

Hey. I would like ActiveRecord to et some DB field automatically using callbacks.

class Product < ActiveRecord::Base
   after_create :set_locale
   def set_locale
      self.locale = I18n.locale
   end
end

In ./script/console I do

p = Product.create
p

Field p.locale is not set. What did I do wrong? Thx for help!

+1  A: 

before_create is called before Base.save, since your not saving its not getting called.

Edit:

class Product < ActiveRecord::Base
   before_create :set_locale
   def set_locale
      self.locale = I18n.locale
   end
end

With this in your controller will work how you want it to.

@product = Product.create
@product.save # before_create will be called and locale will be set for the new product
Joey
I wrote wrong yes. after_create also does not work properly.
xpepermint
You have to call save for the callback to be called whether you put before_create or after_create. before_create is what you are looking for, but you must call save for it to do anything.
Joey
A: 

what Joey is saying is that after_create will not work.

use before_create

Omar Qureshi
the problem was with some other fields that I had in my model. Thx...
xpepermint