public
Last active

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8
# 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"
gistfile2.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 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 %>
gistfile3.txt
1 2 3
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))
gistfile4.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
# 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 %>
gistfile5.txt
1
FeedItem Load (0.5ms) SELECT "feed_items".* FROM "feed_items" LIMIT 30

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.