Skip to content

Instantly share code, notes, and snippets.

@niedhui
Last active August 29, 2015 13:56
Show Gist options
  • Save niedhui/8913059 to your computer and use it in GitHub Desktop.
Save niedhui/8913059 to your computer and use it in GitHub Desktop.
execute raw sql in rails app
class MyMigration < ActiveRecord::Migration
def up
create_table :users do
t.string :name
t.integer :age
end
end
end
MyMigration.migrate(:up)
# or MyMigration.new.up
# or not using migration
ActiveRecord::Base.connection.instance_eval do
create_table :users do
t.string :name
t.integer :age
end
end
arel_table = Arel::Table.new(:users)
# insert
insert_arel = arel_table.compile_insert({arel_table[:name] => 'jack', arel_table[:age] => 20})
ActiveRecord::Base.connection.insert(insert_arel)
# select
select_arel = arel_table.project(Arel.sql('*')).take(1)
ActiveRecord::Base.connection.select_one(select_arel)
#result is a hash {id: 1, name: 'jack', age: 20}
count_arel = arel_table.project(Arel.sql('*').count)
ActiveRecord::Base.connection.select_value(select_arel)
distinct_count_arel = arel_table.project(arel_table[:name].count(true))
ActiveRecord::Base.connection.select_value(distinct_count_arel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment