Self[:foo] vs. foo in AR models

I have an ActiveRecord model with a field called default_pic. I can’t
figure out why the first example DOES NOT work and the second one does,
I’m
not sure why I need the self[]

Doesn’t Work

def set_default_pic
default_pic = “d#{(1…8).rand}.gif”
save
end

Works:

def set_default_pic
self[:default_pic] = “d#{(1…8).rand}.gif”
save
end

On Jan 7, 2008 1:57 PM, blinking bear [email protected] wrote:

I have an ActiveRecord model with a field called default_pic. I can’t
figure out why the first example DOES NOT work and the second one does

It’s a Ruby syntax thing.

def set_default_pic
default_pic = “d#{(1…8).rand}.gif”
save
end

That sets a local variable named default_pic. In order to call the
accessor method, you need to do

self.default_pic = “d#{(1…8).rand}.gif”

There’s some page in the pickaxe which describes it. I don’t have it
beside me, sorry.

Pat

On Jan 7, 2008, at 4:04 PM, Pat M. wrote:

save
Pat
It’s also an “ActiveRecord handles attributes with method_missing”
thing.

The idiomatic way of doing the same thing would be to use
ActiveRecord::Base#update_attribute.

def set_default_pic
update_attribute(:default_pic, “d#{(1…8).rand}.gif”)
end

Or, if this is part of a before_create callback, simply:

def set_default_pic
write_attribute(:default_pic, “d#{(1…8).rand}.gif”)
end

assuming, of course, that you have defined Range#rand somewhere to be
a random item from the Range. (If not, perhaps you want (1+rand(8))
instead.)

-Rob

Rob B. http://agileconsultingllc.com
[email protected]