How to execute raw SQL in Rails
Execute raw SQL directly from ActiveRecord::Base or ApplicationRecord inherited from ActiveRecord::Base
sql = 'SELECT * from tables;'
results = ActiveRecord::Base.connection.execute(sql)
results = ApplicationRecord.connection.execute(sql)
# results will contain PG::Result object, eg:
#<PG::Result:0x00007f9eb76637c8 status=PGRES_TUPLES_OK ntuples=1 nfields=7 cmd_tuples=1>
Access results
results.each do |r|
puts r
end
Reference
How do you manually execute SQL commands in Ruby On Rails using NuoDB
Executing raw sql against multiple data bases
Understanding PG Result object