Forum: Ruby on Rails Just update 1 field

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mischa B. (Guest)
on 2006-01-12 00:43
(Received via mailing list)
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.
Mischa B. (Guest)
on 2006-01-12 01:35
(Received via mailing list)
> 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!
Jesse F. (Guest)
on 2006-01-12 02:08
(Received via mailing list)
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/Ba...

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
Mark Reginald J. (Guest)
on 2006-01-12 02:24
(Received via mailing list)
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.
This topic is locked and can not be replied to.