Reputation: 2103
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?
Upvotes: 0
Views: 1601
Reputation: 4471
Unless I'm missing the point of what you're doing here, you're probably looking for before_create
if you'd like it to save when the row is created. Otherwise you'll have to add self.save
to the method, but that will cause extra database calls, so before_create
might 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_timestamp
to be created_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.save
to end of your method with after_create
2) Use Time.now
if the times sort_timestamp
and created_at
don'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
Upvotes: 2