Forum: Ruby on Rails Cannot change attribute with self[:attribute]= or write_attr

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
9e55e903341ca46f5ccaac5f9c81662b?d=identicon&s=25 akrodha (Guest)
on 2007-03-31 20:00
(Received via mailing list)

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

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

<% for vocab in @vocabs %>
<td><%= link_to 'Promote', :action => 'promote', :id => vocab %></td>

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

def promote
  @vocab = Vocab.find(params[:id])
  redirect_to :action => 'list'

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

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?

7c8f8b6eae4dd991e3a9065c68451361?d=identicon&s=25 Wai Tsang (sneptune)
on 2007-04-01 04:27
When promote is called, will be incremented, right?  If you
don't save the record, the new value of will be gone the next
time you tried to access the Vocab model.

In the other word, you would need! in the promote method.
9e55e903341ca46f5ccaac5f9c81662b?d=identicon&s=25 akrodha (Guest)
on 2007-04-01 20:37
(Received via mailing list)
ah yes, that did the trick. Thanks!

I also realized that self[:box] is unnecessary, since I'm not
overwriting any readers or writers.
This topic is locked and can not be replied to.