On 1/02/11 5:19 PM, Chris Mayan wrote:
Ok thanks
It's definitely a synchronous call, in that the database has received the
INSERT/UPDATE command before #save[!] returns.
But, if you're in a transaction you won't be able to see the data in any
other context until the database receives COMMIT when the transaction block
closes.
So just confirming:
Suppose i Have
ARObject, ARObjectObserver, and ARObjectHistory (which is an audit
recording all history changes of an ARObject)
So in rough pseudo code,
In real code:
https://gist.github.com/8e2403de7ad332c3c20b [1]
> Is that right? I won't be able to see the latest history just created
> from within the same transaction until it completes?
Not quite, you won't be able to see it in *other* transactions.
Running the above script says you can see your own inserts, as long as
you explicitly reload your association (since it gets cached). There are
circumstances where you won't be able to see them across transactions,
but that's perhaps out of scope for this question.
This also gives you a minimal test case to play around with to see
exactly when, what and where is executed.
Cheers,
Xavier
[1]
require 'logger'
require 'active_record'
require 'mysql2'
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.configurations = {'development' => {'adapter' =>
'mysql2', 'user' => 'root', 'database' => 'test'}}
ActiveRecord::Base.establish_connection('development')
ActiveRecord::Schema.define :version => 0 do
create_table :ar_objects, :force => true do |t|
t.string :status
end
create_table :ar_object_histories, :force => true do |t|
t.references :ar_object
t.string :desc
end
end
class ArObject < ActiveRecord::Base
has_many :ar_object_histories
def action
transaction do
puts ar_object_histories.inspect
self.status = "actioned"
self.save
add_history!("Actioning")
puts ar_object_histories.inspect
puts ar_object_histories(true).inspect
end
end
def add_history!(desc)
obj_hist = ArObjectHistory.new(:desc => desc)
obj_hist.ar_object = self
obj_hist.save!
end
end
class ArObjectHistory < ActiveRecord::Base
belongs_to :ar_object
end
class ArObjectObserver < ActiveRecord::Observer
observe :ar_object
def before_update(record)
record.add_history!("observer yeah")
end
end
ActiveRecord::Base.observers = [ArObjectObserver]
ActiveRecord::Base.instantiate_observers
obj = ArObject.create!(:status => 'new')
obj.action
--
You received this message because you are subscribed to the Google Groups "Ruby or
Rails Oceania" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rails-oceania?hl=en.