I can't access my model's attributes in the after_create callback... seems like I should be able to right?
controller:
@dog = Dog.new(:color => 'brown', :gender => 'male')
@dog.user_id = current_user.id
@dog.save
model:
class Dog < ActiveRecord::Base
def after_create
logger.debug "[DOG CREATED] color:#{color} gender:#{gender} user:#{user_id}"
end
end
console: (all seems well)
>>Dog.last
=>#<Dog id: 1, color: "brown", gender: "male", user_id: 1>
log: (wtf!?)
...
[DOG CREATED] color: gender:male user
...
Some of my attributes show up and others don't! oh no! Anyone know what I'm doing wrong? I've always been able to user after_create in such ways in the past.
Note: The actual variable names and values I used were different, but the methods and code are the same.
Figured out my own problem.
One of the attributes was a virtual one, in which I used self.update_attribute...oops!
def price=(amt)
self.update_attribute(:price_in_cents, (amt*100.0).to_i)
end
So for the record, update_attribute will actually create database record (and trigger after_create) if it hasn't been created yet.
Next time I'll be sure to post full code!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With