Just update 1 field


#1

Hi All,

I wonder how I can get rails to update just one field when I do
Myfile.save.

Right now this happens when I do a Myfile.save:

UPDATE myfiles SET folder_id = 0, filesize = 1, data =
‘2f7573722f6c6f63616c2f6d … f7061636b65743d33324d’, user_id = 0,
date_modified = ‘2006-01-11T23:33:57+0100’, filename =
‘mysqlscripts.sql’ WHERE id = 4

but when just the filename has changed I’d rather see something like
this:

UPDATE myfiles SET filename = ‘mysqlscripts.sql’ WHERE id = 4

Is this possible? How?

Thanks.

Mischa.


#2

UPDATE myfiles SET filename = ‘mysqlscripts.sql’ WHERE id = 4

OK, the way to do this is obviously:

myfiles = Myfile.find_by_sql("SELECT id, filename, date_modified,
folder_id FROM myfiles WHERE id = " + @params[:id])

How do I prevent SQL injection when using find_by_sql? This doesn’t seem
to work:

myfiles = Myfile.find_by_sql(“SELECT id, filename, date_modified,
folder_id FROM myfiles WHERE id = ?”, @params[:id])

Thanks again!


#3

Mischa B. wrote:

Hi All,

I wonder how I can get rails to update just one field when I do
Myfile.save.

http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M000766

As for SQL injection with find_by_sql, it follows the same convention as
every other place where bound parameters are appropriate. Rather than
passing multiple arguments you pass in one array, e.g.,
MyModel.find_by_sql([‘select * from widgets where foo = ?’, @foo])

Jesse F. removed_email_address@domain.invalid
University of Chicago - NSIT Web Services
AIM: farmerje
Jabber: removed_email_address@domain.invalid
Phone: (773)363-1058


#4

Mischa B. wrote:

I wonder how I can get rails to update just one field when I do
Myfile.save

but when just the filename has changed I’d rather see something like this:

UPDATE myfiles SET filename = ‘mysqlscripts.sql’ WHERE id = 4

Myfile.update_all( “filename = ‘mysqlscripts.sql’”, ‘id = 4’ )


We develop, watch us RoR, in numbers too big to ignore.