Skip to content

@trevorturk /gist:566272
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
# db/schema.rb
create_table "feed_items", :force => true do |t|
t.integer "user_id"
t.integer "post_id"
t.datetime "post_created_at"
end
add_index "feed_items", ["user_id", "post_created_at"], :name => "index_feed_items_on_user_id_and_post_created_at"
# app/models/user.rb
class User < ActiveRecord::Base
has_many :feed_items
has_many :posts
end
# app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user
end
# app/controllers/feed_items_controller.rb
class FeedItemsController < ApplicationController
def index
@feed_items = current_user.feed_items.all(:limit => 30, :order => 'feed_items.post_created_at', :include => {:post => :user})
end
end
# app/views/feed_items/index.html.erb
<% @feed_items.each do |feed_item| %>
<p><%= feed_item.post.body %></p>
<p>by <%= feed_item.user.name %></p>
<% end %>
FeedItem Load (0.5ms) SELECT "feed_items".* FROM "feed_items" LIMIT 30
Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE ("posts"."id" IN (2,3))
User Load (0.5ms) SELECT "users".* FROM "users" WHERE ("users"."id" IN (1,2))
# Gemfile
gem 'json'
# db/schema.rb
create_table "feed_items", :force => true do |t|
t.integer "user_id"
t.integer "post_id"
t.datetime "post_created_at"
t.text "post_cache" # adding this column
end
add_index "feed_items", ["user_id", "post_created_at"], :name => "index_feed_items_on_user_id_and_post_created_at"
# app/models/post.rb
class Post < ActiveRecord::Base
def to_cache
to_json :include => { :user => { :only => [:name] } }
end
end
# app/models/feed_item.rb
class FeedItem < ActiveRecord::Base
before_save :cache_post
def cache_post
self.post_cache = post.to_cache
end
def cached_post
JSON.parse(post_cache)['post']
end
end
# app/controllers/feed_items_controller.rb
class FeedItemsController < ApplicationController
def index
@feed_items = current_user.feed_items.all(:limit => 30, :order => 'feed_items.post_created_at')
end
end
# app/views/feed_items/index.html.erb
<% @feed_items.each do |feed_item| %>
<p><%= feed_item.cached_post['body'] %></p>
<p>by <%= feed_item.cached_post['user']['name'] %></p>
<% end %>
FeedItem Load (0.5ms) SELECT "feed_items".* FROM "feed_items" LIMIT 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.