Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails after_create callback can't access model's attributes

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.

like image 324
tybro0103 Avatar asked Oct 14 '22 07:10

tybro0103


1 Answers

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!

like image 169
tybro0103 Avatar answered Oct 18 '22 15:10

tybro0103