Reputation: 3454
According to the docs, in Rails models, transactions are made on either classes descending from ActiveRecord::Base
or any instance of such a class. Some blog posts on the subject list the following alternatives:
ActiveRecord::Base.transaction do
User.transaction do
@user.transaction do
self.class.transaction do
self.transaction do
However, I'm missing another variation on this list: How about just transaction do
within model.rb?
class User < ApplicationRecord
def foo
transaction do
# do stuff
end
end
end
Am I right to assume, that the self.
is not really necessary since in the scope of a model instance method, self is always the model instance by default?
Upvotes: 0
Views: 366
Reputation: 102230
In Ruby the implicit recipient in an instance method is always the instance:
class Thing
def foo
inspect
end
end
irb(main):026:0> Thing.new.foo
=> "#<Thing:0x007fde95955828>"
Am I right to assume, that the self. is not really necessary since in the scope of a model instance method, self is always the model instance by default?
There is always an implicit recipient (self) in ruby. What it is depends on the context. In class methods its the class. Its "main" (the global object) if you are not in a class or module.
class Foo
inspect
end
# => "Foo"
def foo
inspect
end
# => "main"
You only have to explicitly use self
where there is a need to disambiguate (like for example self.class
). But there are many situations where it can help the readability of your code.
All of the options above are pretty much functionally equivalent:
ActiveRecord::Base.transaction
connects to the DB for that environment from database.yml
or ENV["DATABASE_URL"]
.User.transaction
or class.transaction
can be used if you want to have different connections per model class or just don't like typing. All it really does is connection.transaction(options, &block)
. self.transaction
or @user.transaction
just proxies to the class method. All it really does is self.class.transaction(options,&block);
Upvotes: 0