Skip to content

Instantly share code, notes, and snippets.

View gabidavila's full-sized avatar
💁‍♀️
I try to solve all my problems with a single SQL query.

Gabriela Ferrara gabidavila

💁‍♀️
I try to solve all my problems with a single SQL query.
View GitHub Profile
@gabidavila
gabidavila / Test
Created September 8, 2017 17:57
Testing API
aaaa
@gabidavila
gabidavila / Test
Created September 8, 2017 17:56
Testing API
aaaaa
@gabidavila
gabidavila / reduce.js
Last active August 29, 2017 20:13
Reduce implementation
//receives an array, and the callback perform an operation
//
function reduce(array, callback, initialValue) {
let acumulator = initialValue ? initialValue : array[0];
let i = initialValue ? 0 : 1;
for (; i < array.length; i++) {
acumulator = callback(acumulator, array[i])
}
return acumulator
INSERT INTO songs (title, artist_id, created_at, updated_at)
VALUES ('We will Rock you', 21474836481, now(), now());
class CreateSongs < ActiveRecord::Migration
def change
create_table :songs do |t|
t.string :title
t.integer :artist_id, limit: 8
t.timestamps
end
add_index :songs, :title
class CreateArtists < ActiveRecord::Migration
def change
create_table :artists do |t|
t.string :name
t.timestamps
end
add_index :artists, :name
end

Using Active Record migrations beyond SQLite

SQLite is really a good tool to set up quick proof of concepts and small applications, however it's not the most robust solution on the market to work with relational databases. In the open source community two databases take the top of the list: PostgreSQL and MySQL.

I did a small project for my studies, and I was using SQLite as I didn't need much out of it. Curious, I decided to see how the application would behave on the other databases and decided to try PostgreSQL and MySQL. I had two problems to solve, and this post is about the first one: how to deal with the migrations. They were as follows:

class CreateArtists < ActiveRecord::Migration[5.1]
  def change
SELECT
`captains`.*
FROM
`captains`
WHERE
`captains`.`id` IN (SELECT
`boats`.`captain_id`
FROM
`boats`
WHERE
SELECT
`captains`.*
FROM
`captains`
INNER JOIN
`boats` ON `boats`.`captain_id` = `captains`.`id`
INNER JOIN
`boat_classifications` ON `boat_classifications`.`boat_id` = `boats`.`id`
INNER JOIN
`classifications` ON `classifications`.`id` = `boat_classifications`.`classification_id`
Captain.joins(boats: :classifications).where(classifications: {name: 'Sailboat'})