Last active
June 2, 2016 14:04
-
-
Save aldesantis/a73b5cb2facd34e1094c24a23a9db0d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class House | |
has_many :photos | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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