Cannot change attribute with self[:attribute]= or write_attr

Hey,

I have a model called Vocab with an integer variable named box. I
defined a method named promote which increases box by one:

def promote
self[:box] += 1
end

I put a link in the list.rhtml view created by scaffold


<% for vocab in @vocabs %>

<%= link_to 'Promote', :action => 'promote', :id => vocab %> ...

and created a promote message in the controller, which passes it on to
the model

def promote
@vocab = Vocab.find(params[:id])
@vocab.promote;
redirect_to :action => ‘list’
end

However, this isn’t working; the box variable stays the same. Changing
the model’s method to

def promote
value_before = self[:box]
self[:box] += 1
value_after = self[:box]
logger.error “Oops! First, box was #{value_before} and now it’s
#{value_after}.”
end

produces this in development.log:

Oops! First, box was 4 and now it’s 5.

So the variable box does change, but the database entry probably
hasn’t been updated. I also tried write_attribute, but no luck. What
am I doing wrong?

Thanks.

When promote is called, Vocab.box will be incremented, right? If you
don’t save the record, the new value of Vocab.box will be gone the next
time you tried to access the Vocab model.

In the other word, you would need self.save! in the promote method.

ah yes, that did the trick. Thanks!

I also realized that self[:box] is unnecessary, since I’m not
overwriting any readers or writers.