Skip to content

Instantly share code, notes, and snippets.

@jhbabon
Created May 14, 2012 12:44
Show Gist options
  • Save jhbabon/2693738 to your computer and use it in GitHub Desktop.
Save jhbabon/2693738 to your computer and use it in GitHub Desktop.
Rails Feeds with SQL View and model: proof of concept
# 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
# 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