Rails Execute SQL
Execute SQL with
execute_sql helper inside your Rails apps. Directly in
Simply add this gem into your Gemfile.
And for example call directly in
execute_sql "select count(*) from users where age > 50" # see below for additional options.
OR in your models, controllers, or other parts of app:
ExecuteSQL.run "select count(*) from users where age > 50" # or with different mode # default mode: :print # return array of HashWithIndifferentAccess objects # please remember that arrays can be manipulated with Enumerable methods, but this is *not* a chainable ARel relation ExecuteSQL.run "select * from users where age > 50", mode: :array # return array of User objects ExecuteSQL.run "select * from users where age > 50", mode: :array, klass: User # return single value ExecuteSQL.run "select count(*) from users where age > 50", mode: :single # return array of results ExecuteSQL.run "select * from users where age > 50", mode: :raw # just execute and return nil ExecuteSQL.run "truncate table users", mode: :none
Sample in controller:
class HomeController < ApplicationController def index @users = ExecuteSql.run "select * from users", mode: :raw end end
Add this line to your application's Gemfile:
And then execute:
Options and modes
You can call:
In rails console use helper:
execute_sql "some SQL".
ExecuteSql.run "some SQL" or
ExecuteSQL.run "some SQL".
- import SQL files
- travis CI
- verify with older rails
- more specs
You are welcome to contribute.
The gem is available as open source under the terms of the MIT License.
Some pieces of code I took from another my gem: https://github.com/igorkasyanchuk/rails_db.
Big thank you.