Can someone please explain to me what the difference between ActiveRecord::Base.connection(some table) vs ActiveRecord::Base.connecton.execute(some table) is? Thank You!
CodePudding user response:
Your question is a bit unclear because both methods do not expect a table_name
as an argument.
But in general, ActiveRecord::Base.connection
returns the current database connection of the ActiveRecord::Base
class which can be used to run low level database queries. Whereas your second example, ActiveRecord::Base.connecton.execute(sql_query)
, used the connection and actually executes a SQL query against the database.
From the docs of ActiveRecord::ConnectionHandling#connection
:
connection()
Returns the connection currently associated with the class. This can also be used to “borrow” the connection to do database work unrelated to any of the specific Active Records.
From the docs of ActiveRecord::ConnectionAdapters::DatabaseStatements#execute
execute(sql, name = nil)
Executes the SQL statement in the context of this connection and returns the raw result from the connection adapter. Note: depending on your database connector, the result returned by this method may be manually memory managed. Consider using the
exec_query
wrapper instead.
CodePudding user response:
ActiveRecord::Base.connection
method does not take any parameters and it returns a connection for the current association class
# File activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb, line 90
def connection
self.class.connection
end
ActiveRecord::Base.connection.execute
takes raw SQL and executes that on the currently established connection for the model.
Refer this for more details