Skip to content

Instantly share code, notes, and snippets.

@aldesantis
Last active June 2, 2016 14:04
Show Gist options
  • Save aldesantis/a73b5cb2facd34e1094c24a23a9db0d2 to your computer and use it in GitHub Desktop.
Save aldesantis/a73b5cb2facd34e1094c24a23a9db0d2 to your computer and use it in GitHub Desktop.
class House
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :house
trigger.after(:insert) do
<<-SQL
IF NEW.cover != 't' THEN
IF (SELECT COUNT(*) FROM photos WHERE photos.house_id = NEW.house_id) = 0 THEN
UPDATE photos
SET cover = 't'
WHERE photos.id = NEW.id;
ELSE
UPDATE photos
SET cover = 'f'
WHERE
photos.house_id = NEW.house_id
AND photos.id <> NEW.id;
END IF;
END IF;
SQL
end
trigger.after(:update).of(:cover) do
<<-SQL
IF NEW.cover = 't' THEN
UPDATE photos
SET cover = 'f'
WHERE
photos.house_id = NEW.house_id
AND photos.id <> NEW.id;
END IF;
SQL
end
trigger.after(:delete) do
<<-SQL
IF OLD.cover = 't' THEN
UPDATE photos
SET cover = 't'
WHERE photos.id = (
SELECT photos.id
FROM photos
WHERE photos.house_id = OLD.house_id
ORDER BY created_at DESC
LIMIT 1
);
END IF;
SQL
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment