I have the following model (sort_timestamp is a datetime):
class Post < ActiveRecord::Base
[snip attr_accessible]
acts_as_nested_set
after_create :set_sort_timestamp
private
def set_sort_timestamp
self.sort_timestamp = self.created_at
end
end
I’m using https://github.com/collectiveidea/awesome_nested_set . This code doesn’t set sort_timestamp. What am I doing wrong?
Unless I’m missing the point of what you’re doing here, you’re probably looking for
before_createif you’d like it to save when the row is created. Otherwise you’ll have to addself.saveto the method, but that will cause extra database calls, sobefore_createmight be the better option.(Basically, the flow of what you were doing before was that the model would be created, saved to the database, and then the object would modify its attribute
sort_timestampto becreated_at; this is after your database commit, and only performed in memory (so not persisted, unless you were persisting it in another way later in the code).EDIT: Actually, this probably won’t work because created_at probably won’t be set before the record is created. A few options:
1) Add
self.saveto end of your method withafter_create2) Use
Time.nowif the timessort_timestampandcreated_atdon’t have to be exactly the same.or, 3) Try adding default value to migration: How to use created_at value as default in Rails