On Thursday, July 17, 2014 12:02:01 PM UTC-7, Jeremy Evans wrote:
>
> On Thursday, July 17, 2014 11:56:57 AM UTC-7, Dan Tenenbaum wrote:
>>
>> Hi,
>>
>> I defined some hooks in Sequel::Model because I want them to be called
>> for all subclasses:
>>
>> require 'time'
>> class Sequel::Model
>>
>> def after_save
>> super
>> puts "IN AFTER_SAVE!"
>> ds = DB[:timestamp]
>> ds.where(true).update(:timestamp => Time.now)
>> end
>>
>> def after_destroy
>> super
>> puts "IN AFTER_DESTROY!"
>> ds = DB[:timestamp]
>> ds.where(true).update(:timestamp => Time.now)
>> end
>>
>> end
>>
>> timestamp is a table with one column (timestamp, of type Date) and one
>> row. The idea is that when there is any write operation on the database
>> (insert, update, delete) that's done using a model, that this timestamp is
>> updated to the currrent time.
>>
>> The problem is, the hooks are not being called in some cases. Here's an
>> example:
>>
>> *Status*.where(:id=>*1*).update(:status=>*"*foobar4*"*)
>>
>> The status table does get updated, but the timestamp table is not updated
>> by this and I don't see the output of the puts() call .
>>
>> I can trigger the hooks if I do this:
>>
>> y = *Status*.new(:status=>*"*hello*"*)
>>
>> y.save
>>
>> And also (subsequently) this:
>>
>> y.status = *"*goodbye*"*
>>
>> y.save
>>
>> So it seems like Status.where(...).update(...) is not considered an
>> operation on a model, even though it starts by invoking the model name?
>>
>> NB. I do have other hooks which are specific to particular models, but
>> they call super and none of those are involved in this example.
>>
>> This is with sequel 4.9.0 and ruby 2.1.1 on Mac OS X 10.9.4.
>>
> This is expected behavior. You are calling Dataset#update, not
> Model#update, and Dataset#update does not run model hooks. If you want to
> run hooks on all affected model instances:
>
> Status.where(...).all{|s| s.update(...)}
>
> Note that this runs one SELECT query to get the model instances, and then
> one UPDATE query for each model instance. This is different than
> Dataset#update, which will only run a single UPDATE query.
>
> If your database supports it, you are better off writing this as a trigger
> instead of using a model hook.
>
>
Great, I will do that (use triggers).
Thanks,
Dan
> Thanks,
> Jeremy
>
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.