Forum: Ruby on Rails A question about updating selected columns only

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.
314818dfe42ecd04a2b47abfaae5a63c?d=identicon&s=25 Adrian De la Cruz (Guest)
on 2007-06-26 20:29
Hello guys,
Seems like I messed up the first time I tried to send this to the list,
so here it is in the Ruby forums :)

I have a little problem, I don't know how to update a few selected
columns in my model. Here is a little example to illustrate my

Suposse I have a model called Book, which have 2 fields (plus the id
one): title and author.

Now if I type this in the console:
>> b1 = ( :title => "title1", :author => "author1" )

After those commands I have a single record sitting in my book's

Now suposse a second user gets access to the database at the same time
as the first one. So we have 2 consoles running at the same time, now
I will present the commands typed at each console in the exact order
(I know there is no need for different variable names, but for
clarity's sake...):

b1 = Book.find(:first)

b2 = Book.find(:first)

b1.update_attribute( :title, "from console1" )

b2.update_attribute( :author = "from console2" )

Now what I would expecto to have is a record like this:
Book.title = "from console1" = "from console2"

But instead I have:
Book.title = "title1" = "from console2"

Why do I expect that? because I'm updating only THAT attribute, not
trying to save the whole row, if I wanted to save the whole row I
would use something like this after fetching the row with find(:first)

b1 = Book.find(:first)
b1.title = "from console1"

Now intuitively I know those 3 lines above fetch the entire row and
saves the entire row to the database. But with the other examples I
gave earlier I would expect them to fetch the entire row and only
update the selected attribute.

How can I accomplish the behavior I desire?
(It's not necessary to fetch the whole row, maybe could I only fetch
the attributes I intend to modify?)

Thanks a lot for reading this :D
3f38541776a2513a20ea2f1c2d522cb3?d=identicon&s=25 Perry Smith (pedz)
on 2007-06-27 05:37
I don't know the answer to your question but I would watch the log files
and look at the db statements being issued.  Then I would try different
things and see how that affected the db statements.

An instance does not need to have all the fields.  So, selecting only
the field that you want to update should work.

The other idea which you can probably do with Ruby (but I don't know
how) is to fetch the whole thing and delete the attributes (fields) that
you do not want to update.

Good luck.
This topic is locked and can not be replied to.