Forum: Ruby on Rails Passing an SQL fragment in AR save

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.
171ea139761951336b844e708d1547ab?d=identicon&s=25 James Byrne (byrnejb)
on 2009-03-03 17:41
I have a basic model class TestTime with no customization.

class TestTime < ActiveRecord::Base
end

I would like to pass the following SQL fragment as part of an AR save
call to TestTime objects.  How and where would I do this in the model?

"set c_time=current_time"

(current_time is an SQL method, not a variable).
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-03 17:58
(Received via mailing list)
On 3 Mar 2009, at 16:41, James Byrne wrote:

>
> I have a basic model class TestTime with no customization.
>
> class TestTime < ActiveRecord::Base
> end
>
> I would like to pass the following SQL fragment as part of an AR save
> call to TestTime objects.  How and where would I do this in the model?
>
Nothing builtin for that as far as I know. If you dig around in the AR
source you may find a suitable method to overide/piggyback on

Fred
171ea139761951336b844e708d1547ab?d=identicon&s=25 James Byrne (byrnejb)
on 2009-03-03 20:07
Frederick Cheung wrote:
> On 3 Mar 2009, at 16:41, James Byrne wrote:
>> I would like to pass the following SQL fragment as part of an AR save
>> call to TestTime objects.  How and where would I do this in the model?
>>
> Nothing builtin for that as far as I know. If you dig around in the AR
> source you may find a suitable method to overide/piggyback on
>

In AR::Base I find this:

      def update(attribute_names = @attributes.keys)
        quoted_attributes = attributes_with_quotes(false, false,
attribute_names)
        return 0 if quoted_attributes.empty?
        connection.update(
          "UPDATE #{self.class.quoted_table_name} " +
          "SET #{quoted_comma_pair_list(connection, quoted_attributes)}
" +
          "WHERE #{connection.quote_column_name(self.class.primary_key)}
= #{quote_value(id)}",
          "#{self.class.name} Update"
        )
      end

So, I think that something along the lines of:

module HLLARUpdateSQL
  def self.included(base)

      def update_sql(id,fragment)
        return 0 unless fragment
        connection.update(
          "UPDATE #{self.class.quoted_table_name} " +
          "SET #{fragment} " +
          "WHERE #{connection.quote_column_name(self.class.primary_key)}
" +
            "#{quote_value(id)}",
          "#{self.class.name} Update"
        )

      end
  end
end

might serve.  Your thoughts?
This topic is locked and can not be replied to.