Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to alter a record in rails, without first reading it

I want to alter a record, but I don't want to read it out of the database first, because frankly I don't see the point. It's huge and across a network that is slow and expensive. Can it be done (easily)?

Lets say I have a record with 100 fields (for arguments sake) and I want to alter one field in the table. I have a really bad connection to the database (this is true) because it's housed on a different box and there's nothing I can do to change this. Right now I pull down the record and rails validates its contents (because I have serialized bits) I then alter one field (one of the hundred depending on X condition) and save the record again. Which I suppose writes the whole record to the database again, with no knowledge of the fact that I only changed one small bit. (this last bit is assumption)

Now to change one record it's sending a huge amount of data across the network, and it could be that I'm only changing one small small thing.. Also it's doing two queries on the database. First the select * then the update..

So my question.. are there smarter base classes that do this right, to write without read?
Top of my head I would think a setter method for each field with a bool flag for changed. When saving, walk the flags and where true... Does this happen now, if so how do I make use of it?

like image 917
baash05 Avatar asked Mar 26 '12 02:03

baash05


1 Answers

Rails models have the update method, which does a SQL select then an SQL update.

Its use is simple (suppose you have a model named Person)

Person.update(person_id, :user_name => 'New Name')

The drawback is that you have to know beforehand the person id.

But then, you will always have to do a query to find out that. You could write your own SQL to change the column value, with a WHERE clause that searches for the param you have.

Rails models have the update_all method, which does only a SQL update without loading the data. But I wouldn't recommend using it because it doesn't trigger any callbacks or validations that your model may have.

You could use the update_all like this:

Book.update_all "author = 'David'", "title LIKE '%Rails%'"

ps: examples were all taken from the Rails official documentation. If you search for update, or update_all, you'll find both methods in no time.

Take a look there, it's a good place to find out what rails can do.

Rails API link

like image 128
Castilho Avatar answered Nov 15 '22 18:11

Castilho