Created
May 14, 2012 12:44
-
-
Save jhbabon/2693738 to your computer and use it in GitHub Desktop.
Rails Feeds with SQL View and model: proof of concept
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
# copied from the texticle gem documentation: | |
# link: http://tenderlove.github.com/texticle/ | |
class CreateFeeds < ActiveRecord::Migration | |
def self.up | |
sql = <<-SQL | |
CREATE VIEW feeds AS | |
SELECT articles.id AS feedable_id, articles.title AS title, | |
CAST ('Article' AS varchar) AS feedable_type | |
FROM articles | |
UNION | |
SELECT videos.id AS feedable_id, videos.title AS title, | |
CAST ('Videos' AS varchar) AS feedable_type | |
FROM videos | |
SQL | |
execute sql | |
end | |
def self.down | |
sql = "DROP VIEW feeds" | |
execute sql | |
end | |
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
# copied from the texticle gem documentation: | |
# link: http://tenderlove.github.com/texticle/ | |
class Feed < ActiveRecord::Base | |
# We want to reference various models | |
belongs_to :feedable, :polymorphic => true | |
# Feed records are never modified | |
def readonly?; true; end | |
# Our view doesn't have primary keys, so we need | |
# to be explicit about how to tell different | |
# results apart; without this, we can't use :include | |
# to avoid n + 1 query problems | |
def hash | |
[feedable_id, feedable_type].hash | |
end | |
def eql?(result) | |
feedable_id == result.feedable_id and | |
feedable_type == result.feedable_type | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment