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
dilemma:
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 = Book.new ( :title => “title1”, :author => “author1” )
b1.save
After those commands I have a single record sitting in my book’s
database.
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…):
Console1
b1 = Book.find(:first)
Console2
b2 = Book.find(:first)
Console1
b1.update_attribute( :title, “from console1” )
Console2
b2.update_attribute( :author = “from console2” )
Now what I would expecto to have is a record like this:
Book.title = “from console1”
Book.author = “from console2”
But instead I have:
Book.title = “title1”
Book.author = “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”
b1.save
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