# Cannot change attribute with self\[:attribute\]= or write\_attr

**URL:** <https://www.ruby-forum.com/t/cannot-change-attribute-with-self-attribute-or-write-attr/90743>\
**Category:** Rails\
**Created:** [March 31, 2007, 8:00pm UTC](https://www.ruby-forum.com/t/cannot-change-attribute-with-self-attribute-or-write-attr/90743 "2007-03-31T20:00:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![akrodha](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8e7dd6/32.png) [@akrodha](https://www.ruby-forum.com/u/akrodha)\
**Post date:** [March 31, 2007, 8:00pm UTC](https://www.ruby-forum.com/t/cannot-change-attribute-with-self-attribute-or-write-attr/90743/1 "2007-03-31T20:00:08Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![akrodha](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8e7dd6/32.png) [@akrodha](https://www.ruby-forum.com/u/akrodha)\
**Post date:** [April 1, 2007, 4:27am UTC](https://www.ruby-forum.com/t/cannot-change-attribute-with-self-attribute-or-write-attr/90743/2 "2007-04-01T04:27:30Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![akrodha](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8e7dd6/32.png) [@akrodha](https://www.ruby-forum.com/u/akrodha)\
**Post date:** [April 1, 2007, 8:37pm UTC](https://www.ruby-forum.com/t/cannot-change-attribute-with-self-attribute-or-write-attr/90743/3 "2007-04-01T20:37:20Z")

</div>

ah yes, that did the trick. Thanks!

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