I am building a public activity stream which contains a stream of the following:
I am using the public_activity gem for achieving this.
My question is whether there is a way to use the includes
for a polymorpic function.
The code that i am running currently is as follows:
#app/models/post.rb
class Post < ActiveRecord::Base
include PublicActivity::Common
attr_accessible :content, :visibility
validates_presence_of :content
belongs_to :postable, :polymorphic => true
has_many :stars
end
#app/models/star.rb
class Star < ActiveRecord::Base
include PublicActivity::Common
validate :duplicate_star
belongs_to :user
belongs_to :post
private
def duplicate_star
errors.add(:base, "Post already starred") if Star.exists?(:user_id => self.user, :post_id => self.post)
end
end
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
@post = Post.new
@activities = PublicActivity::Activity.order("id desc").all.includes(:trackable, :owner)
end
end
The trackable can be a post or a star. I have render functions for displaying both. The problem is, if I try to output something like {user} starred {postcontent}, it does it this way:
activity.trackable.post.content
So this results in multiple queries, each time it finds a post. How do I tackle this problem/situation?
Thanks in advance.
Are you not able to use the standard eager loading syntax?
@activities = PublicActivity::Activity.order("id desc").includes(:owner, :trackable => {:post => :content})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With