Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Setting attribute in after_create

I would like ActiveRecord to set 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?

like image 233
xpepermint Avatar asked Feb 24 '10 15:02

xpepermint


2 Answers

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 # before_create will be called and locale will be set for the new product
like image 137
Joey Avatar answered Nov 08 '22 19:11

Joey


Use before_create to set default values. Remember: after_create is fired after the save to the database. Using after_create will only initialize the values in memory, and will require additional save to commit the initialized values to the database.

like image 29
Guest68 Avatar answered Nov 08 '22 19:11

Guest68